-
Notifications
You must be signed in to change notification settings - Fork 0
/
322. 零钱兑换.cc
63 lines (59 loc) · 1.6 KB
/
322. 零钱兑换.cc
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
62
63
/* 递归法:暴力法 */
class Solution {
public:
/* 递归式f(i)=1+f(i-coins[i]) */
int coinChange(vector<int>& coins, int amount)
{
if(amount == 0) return 0;
int res = INT_MAX;
for(int coin : coins)
{
if(coin > amount) continue;
int subRes = coinChange(coins, amount-coin);
if(subRes == -1) continue;
res = min(res, subRes+1);
}
return res==INT_MAX?-1:res;
}
};
/* 记忆法 */
class Solution {
public:
/* 递归式f(i)=1+f(i-coins[i]) */
int coinChange(vector<int>& coins, int amount)
{
vector<int> vec(amount+1, -2);
return helper(coins, vec, amount);
}
int helper(vector<int> &coins, vector<int> &v, int amount)
{
if(amount == 0) return 0;
if(v[amount] != -2) return v[amount];
int res = INT_MAX;
for(int coin : coins)
{
if(coin > amount) continue;
int subRes = coinChange(coins, amount-coin);
if(subRes == -1) continue;
res = min(res, subRes+1);
}
v[amount] = res==INT_MAX?-1:res;
return v[amount];
}
};
/* 动态规划 */
class Solution {
public:
/* 递归式f(i)=1+f(i-coins[i]) */
int coinChange(vector<int>& coins, int amount)
{
vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int coin : coins)
if (coin <= i)
dp[i] = min(dp[i], dp[i - coin] + 1);
}
return dp[amount] > amount ? -1 : dp[amount];
}
};