A-選択問題(Week 3ジョブ)

6988 ワード

タイトルの説明
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.
Example
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
テーマ構想:
この問題は再帰的に実現することができ、無効な操作を避けるために、前のcountを加えた数字の後ろから選択を開始します.すなわち、再帰時に現在の数字に対応するインデックスを記録するパラメータが1つ多く入力され、次の再帰時にこの数字の次の桁から再帰を開始します.nレイヤを巡回すると、countがちょうど私たちが望んでいる値に等しい場合、ans++、そうでなければ、前のレイヤに戻ります.
コード実装:
#include
using namespace std;
int n,k,s,ans;
int a[16];
bool flag=false;
void fun(int count,int kk,int d)//d           
{
 	if(kk==0)
 	{
  		if(count==s)
  		{
   			ans++;
  			return; 
  		}
 	}
 	else{
  		for(int i=d;i<n;i++)
  		{
   			fun(count+a[i],kk-1,i+1);
  		}
 	}
}
int main()
{
 
 	int N;
 	scanf("%d",&N);
 	while(N--)
 	{
  		ans=0;
  		scanf("%d %d %d",&n,&k,&s);
  		for(int i=0;i<n;i++)
  		{
   			scanf("%d",&a[i]); 
  		}
  		fun(0,k,0);
  		printf("%d
"
,ans); } return 0}