类别:dynamic programming
难度:medium
动态规划
01背包问题
参考连接:http://blog.youkuaiyun.com/hearthougan/article/details/53749841
http://blog.youkuaiyun.com/hearthougan/article/details/53869671
题目描述:
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
.
算法分析
这道题目的算法和背包问题非常相似,对于每种面额,有要和不要两种可能,需要判断要和不要两种可能中使得最终的总的数目最小的那个
即:dp[i] = min(dp[i - 1], dp[i - coin[j]] + 1)
外层循环为总的面额数量的变化,内层循环是对每种面额的钱币选择要还是不要(每种面额的钱币可以重复使用)
代码实现:
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int n = coins.size();
vector<int> result(amount + 1, amount + 1);
result[0] = 0;
// 如果是每种面额的钱币只有一个,那么两层循环的内外可以转换,但是这里每种面额的钱币可以有两个以上
// 所以,每种面额钱币的遍历需要放在内部循环中,可以与背包问题进行比较
for (int i = 1; i <= amount; ++i) {
for (int j = 0; j < n; ++j) {
if (coins[j] <= i) {
result[i] = min(result[i], result[i - coins[j]] + 1);
}
}
}
// 因为初始化的时候是设置为>amount,如果不是刚好能够等于所需要的面额,则不是所要的结果
return result[amount] > amount ? -1 : result[amount];
}
};
注:先理解背包问题,自然就能够很容易地理解这道题目