Advertisement
Oppenheimer

max no of ways (coin change) (1,2 & 2,1 counted once)

Aug 14th, 2022
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. // unbounded knapsack // only difference from 01 is that we can choose one element multiple times.
  2. // here value is weight and as we have to count the number of ways adding value doesnt matter
  3. //knapsack is total sum
  4. int solve(vector<int> value, int knapsack){
  5.     int  n = value.size();
  6.     vector<vector<int>> dp (n+1 ,vecotr<int>(knapsack+1,0));
  7.     // a represents the ath element .. b represents the knapsack present
  8.     for(int a=0;a<=n;a++) dp[a][0] = 1; // dont select any coin
  9.     for(int a=1;a<=n;a++){
  10.         for(int b=1;b<=knapsack;b++){
  11.             if(value[a-1]<=b){
  12.             dp[a][b] = dp[a][b-value[a-1]] + dp[a-1][b]; //here we can choose ith element again
  13.             }else{
  14.             dp[a][b] = dp[a-1][b]; // cant choose the ath element becuase its weight is more
  15.             }
  16.         }
  17.     }
  18.     return dp[n][knapsack];
  19.  
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement