immuntasir

Untitled

May 4th, 2015
328
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. #include <cstdio>
  2. // Returns true if there is a subset of set[] with sun equal to given sum
  3. bool isSubsetSum(int set[], int n, int sum)
  4. {
  5. // The value of subset[i][j] will be true if there is a subset of set[0..j-1]
  6. // with sum equal to i
  7. bool subset[sum+1][n+1];
  8.  
  9. // If sum is 0, then answer is true
  10. for (int i = 0; i <= n; i++)
  11. subset[0][i] = true;
  12.  
  13. // If sum is not 0 and set is empty, then answer is false
  14. for (int i = 1; i <= sum; i++)
  15. subset[i][0] = false;
  16.  
  17. // Fill the subset table in botton up manner
  18. for (int i = 1; i <= sum; i++)
  19. {
  20. for (int j = 1; j <= n; j++)
  21. {
  22. subset[i][j] = subset[i][j-1];
  23. if (i >= set[j-1])
  24. subset[i][j] = subset[i][j] || subset[i - set[j-1]][j-1];
  25. }
  26. }
  27.  
  28. // uncomment this code to print table
  29. for (int i = 0; i <= sum; i++)
  30. {
  31. for (int j = 0; j <= n; j++)
  32. printf ("%4d", subset[i][j]);
  33. printf("\n");
  34. }
  35.  
  36. return subset[sum][n];
  37. }
  38.  
  39. // Driver program to test above function
  40. int main()
  41. {
  42. int set[] = {3, 34, 4, 12, 5, 2};
  43. int sum = 9;
  44. int n = sizeof(set)/sizeof(set[0]);
  45. if (isSubsetSum(set, n, sum) == true)
  46. printf("Found a subset with given sum");
  47. else
  48. printf("No subset with given sum");
  49. return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment