forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0322-coin-change.cpp
30 lines (25 loc) · 804 Bytes
/
0322-coin-change.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
/*
Given array of coins & an amount, return fewest coins to make that amount
Ex. coins = [1,2,5], amount = 11 -> 3, $11 = $5 + $5 + $1
Compute all min counts for amounts up to i, "simulate" use of a coin
Time: O(m x n) -> m = # of coins, n = amount
Space: O(n)
*/
classSolution {
public:
intcoinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for (int i = 1; i < amount + 1; i++) {
for (int j = 0; j < coins.size(); j++) {
if (i - coins[j] >= 0) {
dp[i] = min(dp[i], 1 + dp[i - coins[j]]);
}
}
}
if (dp[amount] == amount + 1) {
return -1;
}
return dp[amount];
}
};