fork download
  1. //
  2. // main.cpp
  3. // Subset with given sum
  4. //
  5. // Created by Himanshu on 18/09/21.
  6. //
  7.  
  8. #include <iostream>
  9. using namespace std;
  10. const int N = 7;
  11.  
  12. int solve (int A[], int sum) {
  13. int dp[sum+1][N+1];
  14.  
  15. // Zero sum is possible with empty subset
  16. for (int i=0; i<=N; i++) {
  17. dp[0][i] = 1;
  18. }
  19.  
  20. // If subset is empty then any sum
  21. // greater than 0 is not possible
  22. for (int i=1; i<=sum; i++) {
  23. dp[i][0] = 0;
  24. }
  25.  
  26. for (int i=1; i<=sum; i++) {
  27. for (int j=1; j<=N; j++) {
  28. dp[i][j] = dp[i][j-1];
  29. if (i >= A[j-1]) {
  30. dp[i][j] = dp[i][j] + dp[i-A[j-1]][j-1];
  31. }
  32. }
  33. }
  34.  
  35. return dp[sum][N];
  36.  
  37. }
  38.  
  39. int main() {
  40. int A[N] = {5, 3, 4, 6, 8, 11, 20};
  41. int sum = 15;
  42. if (solve(A, sum) != 0) {
  43. cout<<"Subset with sum "<<sum<<" is present"<<endl;
  44. } else {
  45. cout<<"No subset with given sum "<<sum<<" is present"<<endl;
  46. }
  47.  
  48. sum = 60;
  49. if (solve(A, sum) != 0) {
  50. cout<<"Subset with sum "<<sum<<" is present"<<endl;
  51. } else {
  52. cout<<"No subset with given sum "<<sum<<" is present"<<endl;
  53. }
  54. }
  55.  
Success #stdin #stdout 0.01s 5512KB
stdin
Standard input is empty
stdout
Subset with sum 15 is present
No subset with given sum 60 is present