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. for (int i=1; i<=sum; i++) {
  16. for (int j=1; j<=N; j++) {
  17. dp[i][j] = 0;
  18. }
  19. }
  20.  
  21. dp[0][0] = 1;
  22. for (int i=1; i<=N; i++) {
  23. dp[0][i] = 1;
  24. }
  25.  
  26. for (int i=1; i<=sum; i++) {
  27. dp[i][0] = 0;
  28. }
  29.  
  30. for (int i=1; i<=sum; i++) {
  31. for (int j=1; j<=N; j++) {
  32. dp[i][j] = dp[i][j-1];
  33. if (A[j-1] <= i) {
  34. dp[i][j] = dp[i][j] + dp[i-A[j-1]][j-1];
  35. }
  36. }
  37. }
  38.  
  39. return dp[sum][N];
  40.  
  41. }
  42.  
  43. int main() {
  44. int A[N] = {5, 3, 4, 6, 8, 11, 20};
  45. int sum = 15;
  46.  
  47. cout<<"Number of subsets with sum "<<sum<<": "<<solve(A, sum)<<endl;
  48.  
  49. sum = 57;
  50. cout<<"Number of subsets with sum: "<<sum<<": "<<solve(A, sum)<<endl;
  51. }
  52.  
Success #stdin #stdout 0.01s 5384KB
stdin
Standard input is empty
stdout
Number of subsets with sum 15: 3
Number of subsets with sum: 57: 1