-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0518-coin-change-ii.cpp
39 lines (33 loc) · 1021 Bytes
/
0518-coin-change-ii.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
Given array of coins & an amount, return # of combos that make up this amount
Ex. amount = 5, coins = [1,2,5] -> 4 (5, 2+2+1, 2+1+1+1, 1+1+1+1+1)
DFS + memo, 2 choices: either try coin & stay at idx, or don't try & proceed
Time: O(m x n)
Space: O(m x n)
*/
class Solution {
public:
int change(int amount, vector<int>& coins) {
return dfs(amount, coins, 0, 0);
}
private:
// {(index, sum) -> # of combos that make up this amount}
map<pair<int, int>, int> dp;
int dfs(int amount, vector<int>& coins, int i, int sum) {
if (sum == amount) {
return 1;
}
if (sum > amount) {
return 0;
}
if (i == coins.size()) {
return 0;
}
if (dp.find({i, sum}) != dp.end()) {
return dp[{i, sum}];
}
dp[{i, sum}] = dfs(amount, coins, i, sum + coins[i])
+ dfs(amount, coins, i + 1, sum);
return dp[{i, sum}];
}
};