选数问题
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,