fork(2) download
  1. int answer;
  2. // Returns true if there is a subset of set[] with sun equal to given sum
  3. int isSubsetSum(int set[], int n, int sum)
  4. {
  5. // Base Cases
  6. if (sum == 0) {
  7. answer++;
  8. return 0; //return false here as we are after all the sums
  9. }
  10. if (n == 0 && sum != 0)
  11. return 0;
  12.  
  13. // If last element is greater than sum, then ignore it
  14. if (set[n-1] > sum)
  15. return isSubsetSum(set, n-1, sum);
  16.  
  17. /* else, check if sum can be obtained by any of the following
  18.   (a) including the last element
  19.   (b) excluding the last element */
  20. return isSubsetSum(set, n-1, sum) || isSubsetSum(set, n-1, sum-set[n-1]);
  21. }
  22.  
  23. // Driver program to test above function
  24. int main()
  25. {
  26. int set[] = {3, 34, 4, 12, 5, 2};
  27. int sum = 9;
  28. int n = sizeof(set)/sizeof(set[0]);
  29. isSubsetSum(set, n, sum);
  30. printf("total %d\n", answer);
  31. return 0;
  32. }
Success #stdin #stdout 0s 2052KB
stdin
Standard input is empty
stdout
total 2