部分和问题:

360 篇文章 3 订阅
88 篇文章 5 订阅

给定整数 a 1 a_1 a 1​ , a 2 a_2 a 2​ , … \dots …, a n a_n a n​ ,判断是否可以从中选出若干数,使得它们的和恰好等于 k k k。
第一行输入一个整数 n n n,表示有几个数据
第二行输入 n n n个整数,表示 a i a_i a
第三行输入一个整数,表示 k k k
限制条件:

  • 1 ≤ n ≤ 20 1\leq n \leq 20 1≤n≤2
  • − 1 0 8 ≤ a i ≤ 1 0 8 -10^8 \leq a_i \leq 10^8 −10 8 ≤a i
    ​ ≤10 8
  • − 1 0 8 ≤ k ≤ 1 0 8 -10^8 \leq k \leq 10^8 −10 8 ≤k≤10 8

样例输入1:

4
1 2 4 7
13

样例输出2:

Yes

样例输入2:

4
1 2 4 7
15

样例输出:

No

深度优先搜索的递归使用,分析如下:在这里插入图片描述
总之就是疯狂的递归就完事了,不好想啊,还在再练

#include<iostream>
#include<string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<deque>
#include<cctype>
#include<unordered_set> 
#include<unordered_map> 
#include<fstream>
using namespace std;
int n,k;
int a[100000]; 
bool dfs(int i,int sum){
	if(i==n) return sum==k;
	if(dfs(i+1,sum+a[i])) return true;
	if(dfs(i+1,sum)) return true;
	return false;
}
int main(){
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	cin>>k;
	if(dfs(0,0)) cout<<"Yes";
	else cout<<"No";
	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_努力努力再努力_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值