Skip to content

Commit 774b1a3

Browse files
authored
Update coin_change_2.cpp
1 parent 456f323 commit 774b1a3

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

cpp/neetcode_150/14_2-d_dynamic_programming/coin_change_2.cpp

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
Time: O(m x n)
88
Space: O(m x n)
99
*/
10-
10+
/*
1111
class Solution {
1212
public:
1313
int change(int amount, vector<int>& coins) {
@@ -37,3 +37,47 @@ class Solution {
3737
return dp[{i, sum}];
3838
}
3939
};
40+
*/
41+
// DP programming solution using a matrix
42+
/*
43+
class Solution {
44+
public:
45+
int change(int amount, vector<int>& coins) {
46+
vector<vector<int>> DP(coins.size() + 1, vector<int>(amount+1));
47+
48+
for (int i = 0; i < coins.size() + 1; ++i)
49+
DP[i][0] = 1;
50+
51+
for (int i = 1; i <= coins.size(); ++i){
52+
for (int j = 0; j <= amount; ++j){
53+
DP[i][j] = DP[i-1][j];
54+
if (j - coins[i-1] >= 0)
55+
DP[i][j] += DP[i][j - coins[i-1]];
56+
}
57+
}
58+
59+
return DP[coins.size()][amount];
60+
}
61+
};
62+
// O(m) space solution
63+
*/
64+
class Solution {
65+
public:
66+
int change(int amount, vector<int>& coins) {
67+
vector<int> prev(amount+1);
68+
vector<int> curr(amount+1);
69+
70+
prev[0] = 1;
71+
72+
for (int i = 0; i < coins.size(); ++i){
73+
for (int j = 0; j <= amount; ++j){
74+
curr[j] = prev[j];
75+
if (j - coins[i] >= 0)
76+
curr[j] += curr[j - coins[i]];
77+
}
78+
prev = curr;
79+
}
80+
81+
return curr[amount];
82+
}
83+
};

0 commit comments

Comments
 (0)