选数问题(DFS) 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!
给定n个正整数,要求选出K个数,使得选出来的K个数的和为sum

输入:
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.

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

样例:
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

思路:
既然是求出符合条件的子集,最笨办法是求出所有元素个数为K的子集,然后一一检验,但显然这样的复杂度不可接受。
运用DFS的思想,暴力地将所有可能情况进行枚举,但与上述思想不同之处在于在向下搜索过程中碰到明显不符合题意(必定无解)的情况要及时停止,这种操作称为“剪枝”。只有这样才能够降低时间复杂度。
本题中,类似之前做过的用递归求子集,在此基础上在递归过程中设置停止条件,即已选择元素个数大于K、已选择元素之和大于S的情况,实现剪枝

代码:

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

int a[20]={1,2,3,4,5,6,7,8,9,10};

int n=10,k=3,s=10;
int count=0;
void solve2(int i,int sum,list<int> &res){
	if(res.size()==k && sum==0){//此方案符合条件 
		count++;
		return;
	}
	
	if(i>=n) return;//边界条件 
	
	if(res.size()>k || sum<0) return;//剪枝 
	
	solve2(i+1,sum,res);//不选此数
	res.push_back(a[i]);
	solve2(i+1,sum-a[i],res);//选用此数 
	res.pop_back();
}

int main(){
	int t;
	list<int> l;
	
	scanf("%d",&t);
	for(int i=0;i<t;i++){
		scanf("%d%d%d",&n,&k,&s);
		for(int j=0;j<n;j++) cin>>a[j];
		solve2(0,s,l);
	    printf("%d\n",count);
	    count=0;
	}
	
	//solve2(0,s,l);
	//printf("%d\n",count);
	return 0;
}

总结:

解决DFS类问题,可以先想出一个简单的、复杂度高的思路,在此基础上设置一些限制条件,实现剪枝,最终达到较为理想的代码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值