题目链接:A-选数问题
题目描述:
Given n positive numbers, ZJM can select exactly K of them that sums to S. Now ZJM wonders how many ways to get it!
给定n个正数,ZJM可以精确地选择其中的K个数,加和为S。现在ZJM想知道有多少方法可以得到它!
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.
第一行,一个整数T<=100,表示测试样例组数。对于每组样例,有两行输入,第一行输入三个整数n,K,S。第二行有n个正整数。
Output:
For each case, an integer indicate the answer in a independent line.
对于每组样例,输出答案。
Sample Input:
1
10 3 10
1 2 3 4 5 6 7 8 9 10
Sample Output:
4
思路:
对于输入的每个数字进行深度搜索,如果查找的数字个数超过K,或着K个数字的和大于S,就结束搜索,符合条件的次数加一,然后对于每一个数字进行递归,直到所有的数字完成搜索。同时在递归过程中排除重复组合。
总结:
每次看到一道题目不是直接想把输出结果弄对,而是要找到适应题解的思路与方法,同时要兼顾方法的多样性和代码的复杂度,以此来优化代码。
代码:
#include<iostream>
using namespace std;
int arr[20],vis[20],count,T,n,k,s;
void dfs(int num,int kk,int sum){
if(kk>k||sum>s)
return;
if(num==n){
if(sum==s&&k==kk)
count++;
return;
}
else if(num<=n){
dfs(num+1,kk,sum);
dfs(num+1,kk+1,sum+arr[num+1]);
}
return;
}
int main(){
int T;
cin>>T;
while(T--){
count=0;
cin>>n>>k>>s;
for(int i=1;i<=n;i++)
cin>>arr[i];
dfs(0,0,0);
cout<<count<<endl;
}
}