Given integers a1, a2, ..., an. Some may judge whether to choose the number, and make them exactly k. (Programming Contest challenge from ch02p30)
1 #include <iostream> 2 3 bool dfs(int ,int ,int ,int,int[]); 4 void solve(int,int,int[]); 5 int main() { 6 using namespace std; 7 8 int num,sum=0; 9 //输入输出 10 cin >> num; 11 int sta[num]; 12 int b = 0 ; 13 is for ( int A = 0 ; A <NUM; A ++ ) { 14 CIN >> B; 15 STA [A] = B; 16 } . 17 18 is int K; . 19 CIN >> K; 20 is // search 21 is Solve (NUM, K, STA); 22 is return 0 ; 23 is } 24 // have been previous item i and the sum, then after branching to the item i 25 BOOL DFS ( int i, int sum, int NUM,int K, int STA []) { 26 is 27 // first n entries have if the calculated, and whether the return is equal to k sum 28 IF (I == NUM) return SUM == K; 29 30 // is not added a [i] in the case 31 is IF (DFS (I + . 1 , SUM, NUM, K, STA)) return to true ; 32 33 is // add a [i] in the case 34 is IF (DFS (I + . 1 , SUM + STA [ I], NUM, k, STA)) return to true ; 35 36 // whether plus without a [i] k can not make up returns to false 37 [ return to false ; 38 is } 39 void solve(int num, int k,int sta[]) { 40 if (dfs(0, 0, num ,k,sta)) printf("Yes\n"); 41 else printf("No\n");
c and c ++ mixed up with. . . In fact, the book is used is c and I will c ++.
Input example
4
1 2 4 7
13
Export
Yes