week3作业题_A-选数问题

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, nn integers indicate the positive numbers.

Output:For each case, an integer indicate the answer in a independent line.

Exmaple:
Input:
1
10 3 10
1 2 3 4 5 6 7 8 9 10
Output:
4

题目思路

在刚看到这个题目的时候,最开始想到的可能是暴力的方法,也就是枚举,可是这种做法的复杂度很高,毫无疑问,这样肯定会TL的。这时候我们就需要再重新整理思路,这时我们可以想到在进行子集枚举的时候我们可以加一些可行性剪枝,排除掉一些不符合要求的情况。
在这里我们进行剪枝的标准主要有两个:(1)子集中选取的数的个数大于K;(2)子集中选取的数大于S。另外还需要考虑到数组的边界。因此剪枝的代码为:

if(theNum > n-1 || li.size() > K || theSum > S) return;		//剪枝

通过dfs方法就很容易得到结果,这里是使用递归实现的。

代码实现

#include <iostream>
#include <list>
using namespace std;

int T , n , K , S , ans;
int a[16];
list<int> li;
 

void solve2(int theNum , int theSum)	//theNum是数组a的起始下标 
{
	if(theSum == S && li.size() == K)
	{
		ans++;			//记录个数 
		return ;
	}
	
	if(theNum > n-1 || li.size() > K || theSum > S) return ;
	
	solve2(theNum + 1 , theSum);		//不选 
	li.push_back(a[theNum]);
	solve2(theNum + 1 , theSum + a[theNum]);		//选 
	li.pop_back(); 
}

int main()
{
	cin >> T;
	for(int i = 0; i < T; i++)
	{
		cin >> n >> K >> S;
		ans = 0;
		for(int j = 0; j < n; j++)
			cin >> a[j];
		
		li.clear();	
		solve2(0 , 0);
		cout << ans <<endl;
	}
	
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值