You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note:
You may assume that you have an infinite number of each kind of coin.
时间复杂度较高,空间复杂度较低的解法:
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if (amount==0)
return 0;
const int len=amount+1;
int dp[len];
for (int i=0;i<len;i++)
dp[i]=INT_MAX;
sort(coins.begin(),coins.end());
priority_queue<int, vector<int>, greater<int>> pqi;
for (int i=0;i<coins.size();i++){
if (coins[i]<=amount){
dp[coins[i]]=1;
pqi.push(coins[i]);
}
}
while (pqi.size()>0){
int head=pqi.top();
pqi.pop();
for (int i=0;i<coins.size();i++)
if (head+coins[i]>amount)
break;
else{
if (dp[ head+coins[i] ]==INT_MAX)
pqi.push(head+coins[i]);
dp[ head+coins[i] ]=min(dp[head]+1, dp[ head+coins[i] ] );
}
}
if (dp[amount]==INT_MAX)
return -1;
else
return dp[amount];
}
};
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if (amount==0)
return 0;
if (coins.empty())
return -1;
const int len=amount+1;
int dp[len];
for (int i=0;i<len;i++)
dp[i]=INT_MAX;
sort(coins.begin(),coins.end());
for (int i=0;i<coins.size();i++){
if (coins[i]<=amount){
dp[coins[i]]=1;
}
}
for (int i=1;i<=amount-coins[0];i++){
if (dp[i]!=INT_MAX)
for (int j=0;j<coins.size();j++)
if (i+coins[j]<=amount)
dp[i+coins[j]]=min(dp[i]+1,dp[i+coins[j]]);
else
break;
}
if (dp[amount]==INT_MAX)
return -1;
else
return dp[amount];
}
};