Week3 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!
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.
Note
Remember that k<=n<=16 and all numbers can be stored in 32-bit integer
Example
Input
1
10 3 10
1 2 3 4 5 6 7 8 9 10
Output
4
解题思路
DFS
递归+递归中判断是否达到目标 中途跳出(剪枝)
Code
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string>
using namespace std;
int st[16];
int n,k,s;
int ans;
void fff(int a,int sum,int t){//递归
if(sum==s){//判断数值
if(t==k){//判断相加次数
ans++;
return;
}
return;
}
for(int i=a;i<n;i++){
sum+=st[i];
fff(i+1,sum,t+1);
sum-=st[i];
}
}
int main(){
int t;
cin>>t;
for(int i=0;i<t;i++){
n=0;k=0;s=0;
cin>>n>>k>>s;
for(int y=0;y<n;y++){
cin>>st[y];
}
//cout<<"cin finish"<<endl;
for(int y=0;y<n-1;y++){//先排序 由小到大
for(int u=0;u<n-y-1;u++){
if(st[u]>st[u+1]){
int temp=st[u];
st[u]=st[u+1];
st[u+1]=temp;
}
}
}
ans=0;
fff(0,0,0);
cout<<ans<<endl;
}
}