File tree Expand file tree Collapse file tree 1 file changed +45
-1
lines changed
cpp/neetcode_150/14_2-d_dynamic_programming Expand file tree Collapse file tree 1 file changed +45
-1
lines changed Original file line number Diff line number Diff line change 7
7
Time: O(m x n)
8
8
Space: O(m x n)
9
9
*/
10
-
10
+ /*
11
11
class Solution {
12
12
public:
13
13
int change(int amount, vector<int>& coins) {
@@ -37,3 +37,47 @@ class Solution {
37
37
return dp[{i, sum}];
38
38
}
39
39
};
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
+ };
You can’t perform that action at this time.
0 commit comments