当前位置:网站首页>LeetCode_322_零钱兑换
LeetCode_322_零钱兑换
2022-08-01 23:54:00 【Fitz1318】
题目链接
题目描述
给你一个整数数组 coins
,表示不同面额的硬币;以及一个整数 amount
,表示总金额。
计算并返回可以凑成总金额所需的 最少的硬币个数 。如果没有任何一种硬币组合能组成总金额,返回 -1
。
你可以认为每种硬币的数量是无限的。
示例 1:
输入:coins = [1, 2, 5], amount = 11
输出:3
解释:11 = 5 + 5 + 1
示例 2:
输入:coins = [2], amount = 3
输出:-1
示例 3:
输入:coins = [1], amount = 0
输出:0
提示:
1 <= coins.length <= 12
1 <= coins[i] <= 2^(31) - 1
0 <= amount <= 10^4
解题思路
动态规划三部曲
- 确定
dp
数组及下标含义dp[j]
:凑成总金额j
所需的最少的硬币个数dp[0] = 0
- 确定递推公式
dp[j] = Math.min(dp[j],dp[j-coin[i]] + 1)
- 确定遍历顺序
- 外层遍历物品,内层遍历背包容量
- 将背包初始化为最大值
amount+1
- 注意需要判断剩余的零钱是不是大于硬币的面值,如果不是,那么就不更新
dp[j]
- 最后判断
dp[amount] > amount ?
AC代码
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
int max = amount + 1;
Arrays.fill(dp, max);
dp[0] = 0;
for (int i = 0; i < coins.length; i++) {
for (int j = 1; j <= amount; j++) {
if (coins[i] <= j) {
dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
}
边栏推荐
- YOLO等目标检测模型的非极大值抑制NMS和评价指标(Acc, Precision, Recall, AP, mAP, RoI)、YOLOv5中[email protected]与
- What can be done to make this SQL into a dangerous SQL?
- 企业防护墙管理,有什么防火墙管理工具?
- 2022第六届强网杯部分wp
- Several interview questions about golang concurrency
- 6132. All the elements in the array is equal to zero - quick sort method
- 几道关于golang并发的面试题
- oozie startup error on cdh's hue, Cannot allocate containers as requested resource is greater than maximum allowed
- ICLR 2022 Best Paper: Partial Label Learning Based on Contrastive Disambiguation
- C language - branch statement and loop statement
猜你喜欢
A brief analysis of mobile APP security testing in software testing, shared by a third-party software testing agency in Beijing
Excel表格数据导入MySQL数据库
洞见云原生微服务及微服务架构浅析
TexturePacker使用文档
Quartus uses tcl files to quickly configure pins
在CentOS下安装MySQL
WEB安全基础 - - - XRAY使用
数据机构---第五章树与二叉树---二叉树的概念---应用题
Docker实践经验:Docker 上部署 mysql8 主从复制
2022还想上岸学习软件测试必看,测试老鸟的肺腑之言...
随机推荐
ansible模块--copy模块
字节跳动面试官:请你实现一个大文件上传和断点续传
Quartus 使用 tcl 文件快速配置管脚
6132. All the elements in the array is equal to zero - quick sort method
cmd command
Special characters & escapes in bat
windows sql server 如何卸载干净?
[LeetCode304 Weekly Competition] Two questions about the base ring tree 6134. Find the closest node to the given two nodes, 6135. The longest cycle in the graph
security 会话并发管理
color transparency parameter
The Spark of Sql join on the and and where
伸展树的特性及实现
正则表达式
Dynamic Scene Deblurring with Parameter Selective Sharing and Nested Skip Connections
云原生DevOps环境搭建
工作5年,测试用例都设计不好?来看看大厂的用例设计总结
Excel文件读写(创建与解析)
在MySQL中使用MD5加密【入门体验】
数据机构---第五章树与二叉树---二叉树的概念---应用题
【MySQL篇】初识数据库