<title>DFS: sections and issues</title> DFS: sections and issues
Given an integer a1, A2 ... an, judging whether a number of them can be selected, so that their and exactly k
Attention:
Each number can only be selected once, of course, also can not choose
// createtime:2015-04-07 22:55:39#include <iostream>using namespace STD;int N;int a[100005];int k;int OK;void DFS(int Step,int sum) {if(n = = Step) {if(sum = = k) {OK = 1; }return; } dfs (step+1, sum); DFS (step+1, sum+a[step]);}int Main(void) {cin >> n; for(int I= 0; I < n; i++) {cin >> a[i]; } cin >> K; OK = 0; DFS (0, 0);if(OK) {cout <<"Yes"<< Endl; }Else{cout <<"No"<< Endl; }return0;}// 4 1 2 4 7// 4 1 2 4 7
I can write more beautiful ideas.
// createtime:2015-04-07 22:55:39#include <iostream>using namespace STD;int N;int a[100005];int k;int OK;int DFS(int Step,int sum) {if(n = = Step) {if(sum = = k) {return1; }Else{return0; } }if(Dfs (step+1, sum)) {return1; }if(Dfs (step+1, sum+a[step])) {return1; }}int Main(void) {cin >> n; for(int I= 0; I < n; i++) {cin >> a[i]; } cin >> K; OK = 0;if(Dfs (0, 0)) {cout <<"Yes"<< Endl; }Else{cout <<"No"<< Endl; }return0;}// 4 1 2 4 7// 4 1 2 4 7
DFS: sections and issues