选数问题(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.

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

我的思路:
这道题的我是利用DFS来解决的。首先题意是有T组数据,在每组数据中,有n个数,要求利用这个n个数中的K个来进行加和,其和等于S的情况数。可以使用深度优先搜索,从一个点出发,顺着一条路径走到已经经过了K个数的情况,判断和是否等与S,是则结果加一,否则不加,然后退回到其上一层,不断进行搜索。

我的代码:

#include<iostream>
using namespace std;

int ci,N,K,S,num[16];

void dfs(int kk,int sum,int d)
{
    if(kk==K)
    {
		if(sum==S) 
		{
			ci++;
		}
	}
    else
    {
        for(int i=d;i<N;i++)
        {
            dfs(kk+1,sum+num[i],i+1);
        }
    }
}

int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {	ci=0;
        cin>>N>>K>>S;
        for(int k=0;k<N;k++)
        {
            cin >> num[k];
        }
        dfs(0,0,0);
        cout<<ci<<endl;
    }
    return 0;
}
发布了26 篇原创文章 · 获赞 0 · 访问量 454

猜你喜欢

转载自blog.csdn.net/qq_43738677/article/details/104675919