DP:
cpp
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int n=coins.size();
vector<int> dp(amount+1,-1);
dp[0]=0;
for(int i=1;i<=amount;i++){
for(int j=0;j<n;j++){
if(i-coins[j]>=0 && dp[i-coins[j]]>=0){
int res=dp[i-coins[j]]+1;
if(dp[i]==-1 || dp[i]>res)
dp[i]=res;
}
}
}
return dp[amount];
}
};
记忆化与回溯:
cpp
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> count(amount+1,0);
function<int(int)> dfs=[&](int amount){
int Min=INT_MAX;
if(amount==0) return 0;
if(amount<0) return -1;
if(count[amount]!=0) return count[amount];
for(auto num:coins){
if(dfs(amount-num)==-1) continue;
if(dfs(amount-num)<Min)
Min=dfs(amount-num)+1;
}
count[amount]=Min==INT_MAX?-1:Min;
return count[amount];
};
return dfs(amount);;
}
};