fork download
  1. // A recursive solution for subset sum problem
  2. #include <stdio.h>
  3. #include <iostream>
  4. using namespace std;
  5. // Returns true if there is a subset of set[] with sun equal to given sum
  6. bool isSubsetSum(int set[], int n, int sum)
  7. {
  8. //cout<<set[n]<<" "<<n<<" "<<sum<<endl; i've printed it to learn what my code is doing
  9. // Base Cases
  10. if (sum == 0)
  11. return true;
  12. if (n == 0 && sum != 0)
  13. return false;
  14.  
  15. // If last element is greater than sum, then ignore it
  16. if (set[n-1] > sum)
  17. return isSubsetSum(set, n-1, sum);
  18.  
  19. /* else, check if sum can be obtained by any of the following
  20.   (a) including the last element
  21.   (b) excluding the last element */
  22. return isSubsetSum(set, n-1, sum) || isSubsetSum(set, n-1, sum-set[n-1]);
  23. }
  24.  
  25. // Driver program to test above function
  26. int main()
  27. {
  28. int set[100];
  29. int sum;
  30. int a, b;
  31. //int n = sizeof(set)/sizeof(set[0]);
  32. cin>>a;
  33. for(int z=0; z<a; z++) {
  34. int n;
  35. cin>>n>>sum;
  36. for(int k=0; k<n; k++) cin>>set[k];
  37. if (isSubsetSum(set, n, sum) == true)
  38. printf("Yes\n");
  39. else
  40. printf("No\n");
  41. }
  42. return 0;
  43. }
Success #stdin #stdout 0s 3300KB
stdin
5
3 3
1
1
1
5 11
1
2
4
8
16
5 23
1
2
4
8
16
5 13
1
5
5
10
10
20 137
17
6
4
998
254
137
259
153
154
3
28
19
123
542
857
23
687
35
99
999
stdout
Yes
Yes
Yes
No
Yes