程序设计思维 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

中文意思

给定n个正整数,要求选出K个数,使得选出来的K个数的和为sum,输出方案
• 例如{1,2,3,4,5,6,7,8,9,10},n=10,K=3,sum=10
• 2+3+5=10
• 1+4+5=10
• 1+3+6=10
• 1+2+7=10

思路

这是一道子集枚举类型的题。
从n个数里面选出k个数共有C(n,k)种选法,且其中只有一很少的一部分才满足k个数之和为sum。
子集问题用递归算法解决的效果很好。
递归算法的设计需要视具体情况而定。
含有n个数的集合共有2^n种子集,显然当n很大时,一个一个地验证子集是不可能会通过oj的,因此递归算法的设计要考虑到:
① 当子集中已经有k个数时,就不能再往下递归(添加数)了,此时必须返回。
② 当子集中所有数之和已经大于或等于sum时,无论子集中是否已经有k个数,都不能再往下递归(添加数)了,此时必须返回。
及时返回、不在无意义(不可能找到目标)的路径下搜索,能节约大量地时间,这被称为可行性剪枝

代码

#include <iostream>
#include <list>

using namespace std;

int t, n, k, s;

int cnt;

int* num;

list<int> li;	// 选的数存在list中

void reset()
{
	n = 0, k = 0, s = 0;
	cnt = 0;
	li.clear();
}

// 递归法
// 判断上一种情况是否需要接着搜索,如果接着搜索,则讨论num[i](0 <= i <= 9)
void solve(int i, int rest)
{
	// 判断
	if (li.size() == k && rest == 0) {
		cnt++;
		return;
	}
	if (i >= n) return;	// 到达边界
	if (li.size() > k || rest < 0) return;	// 可行性剪枝

	solve(i + 1, rest);	// 不选num[i],考虑下一个num[i+1]

	li.push_back(num[i]); //选num[i]
	solve(i + 1, rest - num[i]);
	li.pop_back();
}

int main()
{
	cin >> t;

	for (int i = 0; i < t; i++) {
		reset();
		cin >> n >> k >> s;
		num = new int[n];
		for (int i = 0; i < n; i++) cin >> num[i];
		solve(0, s);
		cout << cnt << endl;
		delete []num;
	}

	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值