当前位置:网站首页>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 <= 121 <= coins[i] <= 2^(31) - 10 <= 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];
}
}
边栏推荐
- Loading configuration of Nacos configuration center
- 6132. All the elements in the array is equal to zero - quick sort method
- 月薪12K,蝶变向新,勇往直前—她通过转行测试实现月薪翻倍~
- 如何进行数据库备份
- @WebServlet注解(Servlet注解)
- solidity
- 架构基本概念和架构本质
- 【ACWing】406. 放置机器人
- Appears in oozie on CDH's hue, error submitting Coordinator My Schedule
- mysql8安装make报错如何解决
猜你喜欢

【MySQL系列】 MySQL表的增删改查(进阶)

CDH6 Hue to open a "ASCII" codec can 't encode characters
![[LeetCode304周赛] 两道关于基环树的题 6134. 找到离给定两个节点最近的节点,6135. 图中的最长环](/img/63/16de443caf28644d79dc6e6889e5dd.png)
[LeetCode304周赛] 两道关于基环树的题 6134. 找到离给定两个节点最近的节点,6135. 图中的最长环

企业防护墙管理,有什么防火墙管理工具?

工作5年,测试用例都设计不好?来看看大厂的用例设计总结

在CDH的hue上的oozie出现,提交 Coordinator My Schedule 时出错

Flink Yarn Per Job - 提交流程一

Data Organization --- Chapter 5 Trees and Binary Trees --- The Concept of Binary Trees --- Application Questions

Share an interface test project (very worth practicing)
![[C language advanced] file operation (2)](/img/4d/49d9603aeed16f1600d69179477eb3.png)
[C language advanced] file operation (2)
随机推荐
根本上解决mysql启动失败问题Job for mysqld.service failed because the control process exited with error code
The third chapter of the imitation cattle network project: develop the core functions of the community (detailed steps and ideas)
【ACWing】406. 放置机器人
FAST-LIO2代码解析(二)
A brief analysis of mobile APP security testing in software testing, shared by a third-party software testing agency in Beijing
Sql之各种Join
Wincc报表教程(SQL数据库的建立,wincc在数据库中保存和查询数据,调用Excel模板把数据保存到指定的位置和打印功能)
字节跳动面试官:请你实现一个大文件上传和断点续传
云原生DevOps环境搭建
solidity
Department project source code sharing
ELK log collection
【Leetcode】470. Implement Rand10() Using Rand7()
cdh6 opens oozieWeb page, Oozie web console is disabled.
如何进行数据库备份
软件测试之移动APP安全测试简析,北京第三方软件检测机构分享
Quartus uses tcl files to quickly configure pins
12306抢票,极限并发带来的思考?
easy-excel 解决百万数据导入导出,性能很强
sys_kill system call