选数问题——dfs

选数问题

Given n positive numbers, ZJM can select exactly K of them that sums to S. Now ZJM wonders how many ways to get it!

Input
The first line, an integer T<=100, indicates the number of test cases. For each case, there are two lines. The first line, three integers indicate n, K and S. The second line, n integers indicate the positive numbers.

Output
For each case, an integer indicate the answer in a independent line.

Example
Input
1
10 3 10
1 2 3 4 5 6 7 8 9 10
Output
4

问题分析

n个数中选k个数,可以看做是组合问题。
以样例为例,10个数 在数组的位置从1 到 10 1 2 3 4 5 6 7 8 9 10
k=3 我们要选择3个数 就相当于有三个位置 __ __ __ 找三个数填上
第一个位置 填1号 第二个位置填2号 那么第三个位置 可以填 3号 4号 5号 6 7 8 9 10号
这些情况完了 第二个位置位置可以填成 3号 那么第三个位置的选择就是 4 5 6 7 8 9 10号

因此,每个数都有选或不选两种情况。
通过dfs深搜我们可以找出所有可能的情况。搜索成功的条件是选的数的个数等于K且选的数的和等于S。此时判定为搜索成功,return。

因为要选k个数,和为S,所以可以进行一次剪枝,当选的数的个数超过K或者选的数的和超过S时,这次搜索判定为失败,体现在代码中就是递归的结束条件。if (num>k||sum>s) return;

代码实现(递归)

#include<stdio.h>
using namespace std;

int n,K,S,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值