题目:
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.
样例
Input
1
10 3 10
1 2 3 4 5 6 7 8 9 10
Output
4
题目思路:
就是一个带有剪枝的枚举,通过递归,参数为当前选择的数i,点的个数k,和s。对于每一个数i都有选择该数和不选择两种情况,若是选择该数那么k-1,s-value[i]进入下一次递归,若是不选择那么k,s不变。
代码
#include<iostream>
using namespace std;
int count=0;
int n;
int *value;
void solve(int i,int k,int s)
{
if(k==0&&s==0)
{
count++;//k=0表示数已经选完,s=0表示符合条件,方案数目++
return;
}
else if(k==0||s<=0||i==n) return;//表示这种选数方案不符合
solve(i+1,k,s);//选择数i进入下一次i+1的递归
solve(i+1,k-1,s-value[i]);//不选择数i
}
int main()
{
int num;
cin>>num;
for(int i=0;i<num;i++)
{
count=0;
int k,s;
cin>>n>>k>>s;
value=new int[n];
for(int j=0;j<n;j++)
cin>>value[j];
solve(0,k,s);
cout<<count<<endl;
}
return 0;
}