当前位置:网站首页>动态规划之换硬币
动态规划之换硬币
2022-08-09 03:15:00 【田园诗人之园】
换硬币 · Coin Change
换硬币 · Coin Change
描述
给出不同面额的硬币以及一个总金额. 写一个方法来计算给出的总金额可以换取的最少的硬币数量. 如果已有硬币的任意组合均无法与总金额面额相等, 那么返回 -1.
你可以假设每种硬币均有无数个
总金额不会超过10000
硬币的种类数不会超过500, 每种硬币的面额不会超过100
样例
样例1
输入:
[1, 2, 5]
11
输出: 3
解释: 11 = 5 + 5 + 1
样例2
输入:
[2]
3
输出: -1
样例3
输入:
[1, 9]
0
输出: 0
题解
解题方法
动态规划是一种解决数学问题的思维,其出发点是借助于前面计算的结果,从而避免重复计算,进而减少计算量,优化计算模型。
该题是一个最值型动态规划类问题,其解题步骤可分如下四步:
- 1,确定状态
- 最后一步(对于该题,最有策略则是要确认最后一枚硬币Ak)
- 化为子问题(用最少的硬币拼接出最小的面值amount - Ak)
- 2,转移方程
- f[x] = min(f[x - coins[j]] + 1, f[x])
- 3,初始条件和边界情况
- f[0] = 0, 若可以拼接出x,则f[x]依赖转移方程计算出有效值,否则f[x] = INT_MAX (无穷大)
- 4,计算顺序
- 动态规划就是要有效利用前面的计算结果去简化运算,所以运算顺序为从前往后计算。
其代码实现如下所示:
C++实现
class Solution {
public:
/** * @param coins: a list of integer * @param amount: a total amount of money amount * @return: the fewest number of coins that you need to make up */
int coinChange(vector<int> &coins, int amount) {
// write your code here
vector<int> dp(amount + 1);
dp[0] = 0;
for (int i = 1; i < amount + 1; i++) {
dp[i] = INT_MAX;
for (int j = 0; j < coins.size(); j++) {
if (i >= coins[j] && dp[i - coins[j]] != INT_MAX) {
dp[i] = min(dp[i], dp[i - coins[j]] + 1);
}
}
}
return dp[amount] == INT_MAX ? -1 : dp[amount];
}
};
边栏推荐
猜你喜欢
随机推荐
QQ浏览器 replaceAll方法 is not a function 问题解决方法
1.02亿美元从数字资产基金撤出!BTC价格已经触底!预示下跌趋势即将逆转?
23 Lectures on Disassembly of Multi-merchant Mall System Functions-Platform Distribution Level
C专家编程 第9章 再论数组 9.7 轻松一下---软件/硬件平衡
Zabbix 5.0 监控教程(五)
VS2019 compiles boost_1_79, generates 32-bit and 64-bit static libraries
powershell 执行策略
关于eBPF与可观测性,你想知道的都在这里
phpStdudy的下载和DVWA的搭建
一本通1258——数字金字塔(动态规划)
SQL注入(4)
Second data CEO CAI data warming invited to jointly organize the acceleration data elements online salon
jsx定义与规则
C专家编程 第9章 再论数组 9.5 数组和指针可交换性的总结
权限系统就该这么设计(万能通用),稳的一批!
【meet host】
【扫雷--2】
Redis expiration strategy and elimination strategy
Promoting practice with competitions-Like the 84th biweekly game reflection and the 305th weekly game supplementary questions
A separate machine is connected to the spark cluster of cdh, and the task is submitted remotely (absolutely successful, I have tested it n times)