给定n个数,以及数k,判断是否能够从n个数中找出任意个数,使其和等于k
1 #include<iostream> 2 #include<malloc.h> 3 using namespace std; 4 int sum_out; 5 int *a; 6 int max; 7 bool dfs(int i,int sum){ 8 9 10 11 if (i == max) return sum == sum_out; 12 13 if (dfs(i + 1, sum))return true; 14 15 16 if (dfs(i + 1, sum + a[i])) return true; 17 18 return false; 19 20 21 22 } 23 int main(){ 24 cout << "max="; 25 cin >> max; 26 cout << endl; 27 cout << "sum="; 28 cin >> sum_out; 29 cout << endl; 30 a = (int *)malloc(sizeof(int)*max); 31 32 for (int i = 0; i < max; i++){ 33 cin >> a[i]; 34 } 35 36 if (dfs(0, 0)) printf("yes\n"); 37 else 38 printf("no\n"); 39 free(a); 40 system("PAUSE"); 41 return 0; 42 }
时间: 2024-12-09 21:23:19