File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int change (int amount, vector<int >& coins) {
4+
5+ int denominations = coins.size ();
6+ int dp[denominations + 1 ][amount + 1 ];
7+
8+
9+ // set first column as 1 as there is 1 way to get sum of 0 irrespective of any denomination of coin that we have
10+ for (int i=0 ; i<=denominations; i++) dp[i][0 ] = 1 ;
11+
12+ // set first row as 0 as irrespective of the sum, for 0 domination we will get 0 ways to reach upto sum
13+ for (int j=1 ; j<=amount; j++) dp[0 ][j] = 0 ;
14+
15+
16+ for (int i=1 ; i<=denominations; i++) {
17+ for (int j=1 ; j<=amount; j++) {
18+
19+ // include exclude principle => similar to unbounded knapsack
20+ if (coins[i-1 ] <= j) {
21+ // exclude + include
22+ dp[i][j] = dp[i-1 ][j] + dp[i][j - coins[i-1 ]]; // in include its i in row and not i-1 because of unbounded knapsack
23+ }
24+ else {
25+ dp[i][j] = dp[i-1 ][j];
26+ }
27+ }
28+ }
29+ return dp[denominations][amount]; // total number of ways, coins of x denomination can get upto target sum
30+ }
31+ };
You can’t perform that action at this time.
0 commit comments