一开始用回溯做,发现即使剪枝也会超时
class Solution {
public:
int ans=0;
int change(int amount, vector<int>& coins) {
func(amount,0,0,coins);
return ans;
}
void func(int amount,int cur,int beg,vector<int>& coins){
if(cur==amount){
ans++;
return ;
}
if(cur>amount) return;
for(int i=beg;i<coins.size();i++){
cur+=coins[i];
func(amount,cur,i,coins);
cur-=coins[i];
}
}
};
使用动态规划做
class Solution {
public:
int change(int amount, vector<int>& coins) {
int dp[amount+1];
memset(dp,0,sizeof(dp));
dp[0]=1;
for(auto coin:coins){
for(int i=coin;i<=amount;i++){
dp[i]+=dp[i-coin];
}
}
return dp[amount];
}
};