题目描述:
解法一(递归):
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if(amount==0) return 0;
int res=INT_MAX;
for(auto coin:coins){
if(coin>amount)
continue;
int rt=coinChange(coins,amount-coin);
if(rt==-1) continue;
res=min(res,rt+1);
}
return res==INT_MAX? -1:res;
}
};
解法二(带备忘录的递归):
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
unordered_map<int,int> mp;
return helper(coins,amount,mp);
}
int helper(vector<int>& coins, int amount, unordered_map<int,int>& mp){
if(amount==0) return 0;
if(mp.count(amount)) return mp[amount];
int res=INT_MAX;
for(auto coin:coins){
if(coin>amount)
continue;
int rt=helper(coins,amount-coin,mp);
if(rt==-1) continue;
res=min(res,rt+1);
}
mp[amount]= res==INT_MAX? -1:res;
return mp[amount];
}
};
解法三(动态规划):
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (auto coin : coins) {
if (coin > i || dp[i - coin] == INT_MAX)
continue;
dp[i] = min(dp[i], dp[i - coin] + 1);
}
}
return dp[amount]==INT_MAX? -1:dp[amount];
}
};