1、题目
https://leetcode-cn.com/problems/coin-change/
2、题意
题解1:dfs 超时 从大到小排序,一次找一个
141 / 182 个通过测试用例
class Solution {
public:
int res = INT_MAX;
void dfs(vector<int> &coins,int first,int cnt,int amount)
{
if(cnt>=res||amount<0) return;
if(amount==0)
res = min(cnt,res);
for(int i=first;i<coins.size();i++)
dfs(coins,i,cnt+1,amount-coins[i]);
}
int coinChange(vector<int>& coins, int amount) {
sort(coins.rbegin(),coins.rend());
dfs(coins,0,0,amount);
return res==INT_MAX?-1:res;
}
};
题解2:优化 贪心+dfs
class Solution {
public:
int res = INT_MAX;
void dfs(vector<int> &coins,int index,int cnt,int amount)
{
if(amount==0)
{res = min(res,cnt);
return;
}
if(index==coins.size()) return;
for(int i=amount/coins[index];i>=0&&i+cnt<res;i--)
dfs(coins,index+1,cnt+i,amount-coins[index]*i);
}
int coinChange(vector<int>& coins, int amount) {
sort(coins.rbegin(),coins.rend());
dfs(coins,0,0,amount);
return res==INT_MAX?-1:res;
}
};
题解3:dp dp[i]表示amount=i时 的最小个数
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount+1,-1);
dp[0] = 0;
for(int i=1;i<=amount;i++)
for(int j=0;j<coins.size();j++)
{
if(i>=coins[j]&&dp[i-coins[j]]!=-1)
{
if(dp[i]>0)
dp[i] = min(dp[i],dp[i-coins[j]]+1);
else
dp[i] = dp[i-coins[j]]+1;
}
}
return dp[amount];
}
};