小偷的背包
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 int s, flag, n, *a; //主函数之外定义的变量为全局变量 5 6 void dfs(int index, int count, int * a) 7 { 8 if(count == s) 9 { 10 flag = 1; 11 return; 12 } 13 14 if (index > n) 15 { 16 return; 17 } 18 19 dfs(index + 1, count + a[index], a); 20 dfs(index + 1, count, a); 21 } 22 23 int main(int argc, char const *argv[]) 24 { 25 scanf("%d",&s); 26 scanf("%d",&n); 27 28 a = (int*)malloc(n*sizeof(int)); 29 30 for (int i = 0; i < n; ++i) 31 { 32 scanf("%d",&a[i]); 33 } 34 35 dfs(0, 0, a); 36 37 if (flag) 38 { 39 printf("yes!"); 40 } 41 else 42 { 43 printf("no!"); 44 } 45 return 0; 46 }