题目: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.
难度:medium 通过率:25.9%
这道题老师在课上讲了一下思路,利用数组f[i]表示金额为i时的最小硬币数,然后当金额为i-coins[j]时,加上硬币j,即f[i-coins[j]]+1和f[i]进行比较,取较小的值,动态更新数组,代码实现如下:
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int size = coins.size();
vector<int> f(amount+1, -1);
f[0] = 0;
for(int i = 1; i <= amount; i++) {
for(int j = 0; j < size; j++) {
if(coins[j] <= i && f[i-coins[j]]!=-1&&(f[i-coins[j]]+1 < f[i] || f[i] == -1)) {
f[i] = f[i-coins[j]] + 1;
}
}
}
return f[amount];
}
};
本文探讨了硬币找零问题的解决方案,采用动态规划的方法,寻找组成特定金额所需的最少硬币数量。提供了详细的代码实现,并附带示例说明。
2633

被折叠的 条评论
为什么被折叠?



