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
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
分析:每一个数有选/不选两种情况,注意列举,判断是否符合要求
。
用回溯法枚举:对于递归函数solve,列出当前数字选或不选的可能,在做出选的动作后,恢复原状态。
剪枝策略:如何所选数字大于K或者和大于s,终止。
代码如下:
#include <iostream>
#include <vector>
using namespace std;
int cnt, n, k, s;
int* numbers;
void solve(int sum, int cur, vector<int>& res)
{
if (res.size() == k && sum == 0)
{
cnt++;
return;
}
if (cur >= n || res.size() > k || sum < 0)
return;
solve(sum, cur + 1, res);
res.push_back(numbers[cur]);
solve(sum - numbers[cur], cur + 1, res);
res.pop_back();
}
int main()
{
int N;
cin >> N;
while (N--)
{
cnt = 0;
cin >> n >> k >> s;
vector<int> res;
numbers = new int[n];
for (int i = 0; i < n; i++)
{
cin >> numbers[i];
}
solve(s, 0, res);
cout << cnt << endl;
}
delete[] numbers;
}