当前位置:网站首页>Snap: 322. Change of Change
Snap: 322. Change of Change
2022-08-10 00:32:00 【empty__barrel】
力扣:322. 零钱兑换
题目:
给你一个整数数组 coins ,表示不同面额的硬币;以及一个整数 amount ,表示总金额.
计算并返回可以凑成总金额所需的 最少的硬币个数 .如果没有任何一种硬币组合能组成总金额,返回 -1 .
你可以认为每种硬币的数量是无限的.
dp【j】的含义:
dp[j]:凑足总额为j所需钱币的最少个数为dp[j]
递推公式:
dp[j] = min(dp[j - coins[i]] + 1, dp[j]);
初始化:
dp【0】为0的原因:amount是可以等于0的,At the same time, it is logically obviousdp【0】 = 0
因为dp[j]Choose the smaller of the two = min(dp[j], dp[j-coins[i]]+1);所以下标非0的元素都是应该是最大值.
遍历顺序:
This question is completely backpack type,So from childhood to adulthood 遍历,At the same time, the minimum number of coins required is not involved in the sequence,所以本题的两个forNesting of loops is not required,谁先谁后都行.
The reason for setting the judgment condition before the recursive function:
因为dp[j] = min(dp[j], dp[j-coins[i]]+1);
If this operationdp[j - coins[i]] == INT_MAX
那么dp[j-coins[i]]+1
就越界了,So we need to set a judgment condition.
代码:
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int>dp(amount+1,INT_MAX);
dp[0] = 0;
for(int i = 0; i < coins.size(); ++i){
for(int j = coins[i]; j <= amount; ++j){
if (dp[j - coins[i]] != INT_MAX) dp[j] = min(dp[j], dp[j-coins[i]]+1);
}
}
if(dp[amount] == INT_MAX) return -1;
return dp[amount];
}
};
边栏推荐
猜你喜欢
随机推荐
多线程是同时执行多个线程的吗
mysql中的key是怎么用的,或者这个值有什么意义,如下图?
力扣:377. 组合总和 Ⅳ
力扣:474.一和零
干货!迈向鲁棒的测试时间适应
【Apifox】为什么如此受青睐,此篇文章和大家分享
tiup cluster scale-out
tiup cluster stop
【Leetcode】2104. Sum of Subarray Ranges
String类常用方法
What is the stability of the quantitative trading interface system?
Pytorch分布式训练/多卡训练DDP——模型初始化(torch.distribute 与 DDP的区别)
正则表达式的实际使用
华为云全流程护航《流浪方舟》破竹首发,打造口碑爆款
【燃】是时候展现真正的实力了!一文看懂2022华为开发者大赛技术亮点
五分钟商学院(基础---商业篇)
金仓数据库 KingbaseGIS 使用手册(6.4. 几何对象存取函数)
pip 离线到内网安装包
matplotlib散点图颜色分组图例
深圳堡垒机厂家有哪些?重点推荐哪家?