选数问题

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值