Week3 HomeWork A 选数问题 DFS+剪枝

3 篇文章 0 订阅

题目描述

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个正整数,ZJM能选择其中k个数,使之和为S。现在ZJM想知道满足条件的选数方案有多少种。

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.

第一行为一个整数T,表示测试用例数。对于每个测试样例,有两行输入。第一行为3个整数n, k, s;第二行为n个正整数。

Remember that k<=n<=16 and all numbers can be stored in 32-bit integer

k<=n<=16,且所有数都在32位整数范围以内

Output

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

对于每个测试用例,在单独的一行输出一个正整数表示方案数。

Sample Input

1
10 3 10
1 2 3 4 5 6 7 8 9 10

Sample Output

4

算法/思路分析

​ 思路:本题是典型的DFS,为防止DFS遍历所有状态导致复杂度过高,这里使用剪枝提前退出DFS过程。具体而言,对于每个数只有选与不选两个选择,而在选择之前,可以在选的个数超过指定个数以及和超过目标数时,直接退出DFS,从而避免很多无用的操作。

代码

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

int a[20]; //记录可选的n个数 
int n,k,s,ans;  

void dfs(int i,int cnt,int sum)
{
	//可行性剪枝:选多了或者选的数之和大于目标数,直接退出
	if(cnt > k || sum > s) return;
	
	//遍历到可选的最后一个数时 
	if(i == n)
	{
		if(cnt == k && sum == s) ans++;  //满足条件,方案数+1
		return; 
	}
	
	dfs(i + 1, cnt, sum); //不选 
	dfs(i + 1, cnt + 1, sum + a[i]);  //选	
		
}

int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d%d",&n,&k,&s);
		for(int i = 0;i < n; i++)
			scanf("%d",&a[i]);
		ans = 0;
		dfs(0,0,0);
		printf("%d\n",ans);
	}
	return 0;	
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值