题目:
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个正整数,要求选出K个数,使得选出来的K个数的和为sum
输入:
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.
输出:
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
Note:
Remember that k<=n<=16 and all numbers can be stored in 32-bit integer
思路:
既然是求出符合条件的子集,最笨办法是求出所有元素个数为K的子集,然后一一检验,但显然这样的复杂度不可接受。
运用DFS的思想,暴力地将所有可能情况进行枚举,但与上述思想不同之处在于在向下搜索过程中碰到明显不符合题意(必定无解)的情况要及时停止,这种操作称为“剪枝”。只有这样才能够降低时间复杂度。
本题中,类似之前做过的用递归求子集,在此基础上在递归过程中设置停止条件,即已选择元素个数大于K、已选择元素之和大于S的情况,实现剪枝。
代码:
#include <iostream>
#include <cstdio>
#include <list>
using namespace std;
int a[20]={1,2,3,4,5,6,7,8,9,10};
int n=10,k=3,s=10;
int count=0;
void solve2(int i,int sum,list<int> &res){
if(res.size()==k && sum==0){//此方案符合条件
count++;
return;
}
if(i>=n) return;//边界条件
if(res.size()>k || sum<0) return;//剪枝
solve2(i+1,sum,res);//不选此数
res.push_back(a[i]);
solve2(i+1,sum-a[i],res);//选用此数
res.pop_back();
}
int main(){
int t;
list<int> l;
scanf("%d",&t);
for(int i=0;i<t;i++){
scanf("%d%d%d",&n,&k,&s);
for(int j=0;j<n;j++) cin>>a[j];
solve2(0,s,l);
printf("%d\n",count);
count=0;
}
//solve2(0,s,l);
//printf("%d\n",count);
return 0;
}
总结:
解决DFS类问题,可以先想出一个简单的、复杂度高的思路,在此基础上设置一些限制条件,实现剪枝,最终达到较为理想的代码。