当前位置:网站首页>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];
}
};
边栏推荐
猜你喜欢
随机推荐
探索TiDB Lightning源码来解决发现的bug
【接口测试】requests 库请求体字符串解码
linux上使用docker安装redis
&&、||、&、|
What are the basic steps to develop a quantitative trading strategy?
毕昇编译器优化:Lazy Code Motion
YGG 经理人杯总决赛已圆满结束,来看看这份文字版总结!
迅为瑞芯微RK3399开发板设置Buildroot文件系统测试MYSQL允许远程访问
金仓数据库 KingbaseGIS 使用手册(6.5. 几何对象编辑函数)
Gartner全球集成系统市场数据追踪,超融合市场增速第一
torch.distributed多卡/多GPU/分布式DPP(二)——torch.distributed.all_reduce(reduce_mean)&barrier&控制进程执行顺序&随机数种子
tiup cluster start
Redis集群
友元类和友元函数
国内十大活跃报表 BI 产品深度对比及点评
“我“是一名测试/开发程序员,小孙的内心独白......
少儿编程 电子学会图形化编程等级考试Scratch三级真题解析(判断题)2022年6月
浅析量股票化交易的发展现状
Mysql集群 ShardingSphere
VR全景拍摄如何拍摄?如何使用拍摄器材?