Leetcode 322. Coin Change
题目描述
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.
输入:硬币种类数组、金额
输出:所需要最少的硬币数;无法满足时返回-1
思路
动态规划:用f[i]表示金额为i时,所需要最少硬币数量。此处,考虑类似滑动窗口的情况。对于每个金额,都可根据硬币的种类,并增加一个硬币到达下一个金额。而到达新的金额时,需要判断取已有硬币数量与新硬币数量的较小值。
首先将硬币根据大小进行排序
Sort(Coins)
其次,对f数组进行初始化,对于已有种类,默认置1,即
for(int i =0;i<coins.size()&&coins[i]<=amount;i++){
f[coins[i]] = 1;
}
状态转移方程:
i=[coins[0],amount]
j=[0,coins.size())
f[i+coins[j]]=min(f[i+coins[j]],f[i]+1)
那么f[amount]就是答案,复杂度 O(n2)
代码
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if(amount==0) return 0;
if(coins.size()==0) return -1;
sort(coins.begin(),coins.end());
vector<int> f(amount+1,amount+1);
for(int i =0;i<coins.size()&&coins[i]<=amount;i++){
f[coins[i]] = 1;
}
for(int i =coins[0];i<=amount;i++){
for(int j=0;j<coins.size()&&(i+coins[j])<=amount&&(i+coins[j]>0);j++){
f[i+coins[j]] = min(f[i+coins[j]], f[i]+1);
}
}
return f[amount]>=amount+1?-1:f[amount];
}
};