程序设计思维与实践 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!
给定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<=100,表示测试样例组数。对于每组样例,有两行输入,第一行输入三个整数n,K,S。第二行有n个正整数。

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

思路:
对于输入的每个数字进行深度搜索,如果查找的数字个数超过K,或着K个数字的和大于S,就结束搜索,符合条件的次数加一,然后对于每一个数字进行递归,直到所有的数字完成搜索。同时在递归过程中排除重复组合。

总结:
每次看到一道题目不是直接想把输出结果弄对,而是要找到适应题解的思路与方法,同时要兼顾方法的多样性和代码的复杂度,以此来优化代码。

代码:

#include<iostream>
using namespace std;
int arr[20],vis[20],count,T,n,k,s;
void dfs(int num,int kk,int sum){
	if(kk>k||sum>s)
		return;
	if(num==n){
		if(sum==s&&k==kk)
			count++;
		return;
	}
	else if(num<=n){
		dfs(num+1,kk,sum);
		dfs(num+1,kk+1,sum+arr[num+1]);
	}
	return;
}
int main(){
	int T;
	cin>>T;
	while(T--){
		count=0;
		cin>>n>>k>>s;
		for(int i=1;i<=n;i++)
		cin>>arr[i];
		dfs(0,0,0);
		cout<<count<<endl; 
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值