当前位置:网站首页>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];
}
}
边栏推荐
猜你喜欢
【Leetcode】1206. Design Skiplist
mysql8安装make报错如何解决
分享一份接口测试项目(非常值得练手)
获取小猪民宿(短租)数据
在MySQL登录时出现Access denied for user ‘root‘@‘localhost‘ (using password YES) 拒绝访问问题解决
Secondary Vocational Network Security Competition B7 Competition Deployment Process
经典文献阅读之--DLO
GIF制作-灰常简单的一键动图工具
DVWA靶场环境搭建
[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
随机推荐
Excel表格数据导入MySQL数据库
color transparency parameter
Convert LocalDateTime to Date type
TexturePacker使用文档
FAST-LIO2 code analysis (2)
[C language advanced] file operation (2)
Several interview questions about golang concurrency
工作5年,测试用例都设计不好?来看看大厂的用例设计总结
【ACWing】230. 排列计数
Excel文件读写(创建与解析)
ansible模块--copy模块
2022还想上岸学习软件测试必看,测试老鸟的肺腑之言...
学习笔记:机器学习之回归
信息系统项目管理师必背核心考点(五十七)知识管理工具
一款简洁的文件传输工具
[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
EasyExcel的简单读取操作
技术分享 | 接口测试中如何使用Json 来进行数据交互 ?
ICLR 2022 Best Paper: Partial Label Learning Based on Contrastive Disambiguation
【MySQL系列】MySQL索引事务