给定整数 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;
}