-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCoin Change.cpp
61 lines (59 loc) · 1.5 KB
/
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// //Solution I
// class Solution {
// public:
// int solve(vector<int>& coins, int amount){
// if(amount == 0){
// return 0;
// }
// if(amount < 0){
// return INT_MAX;
// }
// int mini = INT_MAX;
// for(int i = 0; i < coins.size(); i++){
// int ans = solve(coins, amount-coins[i]);
// if (ans != INT_MAX){
// mini = min(mini, ans+1);
// }
// }
// return mini;
// }
// int coinChange(vector<int>& coins, int amount) {
// int ans = solve(coins, amount);
// if(ans == INT_MAX){
// return -1;
// }
// return ans;
// }
// };
//Solution II
class Solution {
public:
int solve(vector<int>& coins, int amount,vector<int>& dp){
if(amount == 0){
return 0;
}
if(amount < 0){
return INT_MAX;
}
if(dp[amount] != -1){
return dp[amount];
}
int mini = INT_MAX;
for(int i = 0; i < coins.size(); i++){
int ans = solve(coins, amount-coins[i], dp);
if (ans != INT_MAX){
mini = min(mini, ans+1);
}
}
dp[amount] = mini;
return dp[amount];
}
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount+1, -1);
int ans = solve(coins, amount, dp);
if(ans == INT_MAX){
return -1;
}
return ans;
}
};