Skip to content

Commit

Permalink
Update coin_change_2.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
caba5 authored Dec 13, 2022
1 parent 456f323 commit 774b1a3
Showing 1 changed file with 45 additions and 1 deletion.
46 changes: 45 additions & 1 deletion cpp/neetcode_150/14_2-d_dynamic_programming/coin_change_2.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
Time: O(m x n)
Space: O(m x n)
*/

/*
class Solution {
public:
int change(int amount, vector<int>& coins) {
Expand Down Expand Up @@ -37,3 +37,47 @@ class Solution {
return dp[{i, sum}];
}
};
*/
// DP programming solution using a matrix
/*
class Solution {
public:
int change(int amount, vector<int>& coins) {
vector<vector<int>> DP(coins.size() + 1, vector<int>(amount+1));
for (int i = 0; i < coins.size() + 1; ++i)
DP[i][0] = 1;
for (int i = 1; i <= coins.size(); ++i){
for (int j = 0; j <= amount; ++j){
DP[i][j] = DP[i-1][j];
if (j - coins[i-1] >= 0)
DP[i][j] += DP[i][j - coins[i-1]];
}
}
return DP[coins.size()][amount];
}
};
// O(m) space solution
*/
class Solution {
public:
int change(int amount, vector<int>& coins) {
vector<int> prev(amount+1);
vector<int> curr(amount+1);

prev[0] = 1;

for (int i = 0; i < coins.size(); ++i){
for (int j = 0; j <= amount; ++j){
curr[j] = prev[j];
if (j - coins[i] >= 0)
curr[j] += curr[j - coins[i]];
}
prev = curr;
}

return curr[amount];
}
};

0 comments on commit 774b1a3

Please sign in to comment.