Given nn positive numbers, ZJM can select exactly KK of them that sums to SS. Now ZJM wonders how many ways to get it!InputThe first line, an integer T<=100T<=100, indicates the number of test cases. For each case, there are two lines. The first line, three integers indicate nn, KK and SS. The second line, nn integers indicate the positive numbers.OutputFor 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
Note
Remember that k<=n<=16k<=n<=16 and all numbers can be stored in 32-bit integer
Sponsor
解题思路:
这是选数问题,采用DFS的思想,对这n个数进行遍历。不过其中有很多情况其实是不需要遍历的,所以我们可以进行剪枝。这里采用的是重复性剪枝。从第一个数开始选,选取数的位置是递增的。用一个参数来记录上一次选取的数的位置,此次选择从这个数之后开始选取。
#include <iostream>
#include<cstring>
using namespace std;
int n, k, sum, ans;
int a[40];
bool xuan[40];
void dfs(int s, int cnt,int pos) {
if(s>sum||cnt>k){
return ;
}
if (s == sum && cnt == k) {
ans++;
}
for (int i = pos; i < n; i++) {
if (!xuan[i]) {
xuan[i] = true;
dfs(s + a[i], cnt + 1,i+1);
xuan[i] = false;
}
}
}
int main() {
int t;
scanf("%d",&t);
for(int i=0;i<t;i++)
{
scanf("%d%d%d",&n,&k,&sum);
memset(a,0,sizeof(a));
memset(xuan,false,sizeof(xuan));
for (int j= 0; j<n; j++) {
scanf("%d",&a[j]);
}
ans = 0;
dfs(0, 0,0);
cout << ans << endl;
}
return 0;
}
//重复性剪枝:
//选出来的数的位置是递增的,用一个参数来记录上一次选取的数的位置,此次选择从这个数之后开始选取,最后选出来的方案不会重复