当前位置:网站首页>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];
}
}
边栏推荐
- 【Leetcode】2360. Longest Cycle in a Graph
- GIF制作-灰常简单的一键动图工具
- 带你搞懂MySQL隔离级别,两个事务同时操作同一行数据会怎样?
- ICLR 2022 Best Paper: Partial Label Learning Based on Contrastive Disambiguation
- FAST-LIO2代码解析(二)
- With a monthly salary of 12K, the butterfly changed to a new one and moved forward bravely - she doubled her monthly salary through the career change test~
- Excel文件读写(创建与解析)
- contentEditable属性
- DVWA靶场环境搭建
- JAX-based activation function, softmax function and cross entropy function
猜你喜欢

Flink Yarn Per Job - Yarn应用

C language - branch statement and loop statement

Excel表格数据导入MySQL数据库

Architecture basic concept and nature of architecture

The third chapter of the imitation cattle network project: develop the core functions of the community (detailed steps and ideas)

Dynamic Scene Deblurring with Parameter Selective Sharing and Nested Skip Connections

Appears in oozie on CDH's hue, error submitting Coordinator My Schedule

伸展树的特性及实现

ICLR 2022 Best Paper: Partial Label Learning Based on Contrastive Disambiguation

yay 报错 response decoding failed: invalid character ‘<‘ looking for beginning of value;
随机推荐
GetHashCode与Equals
【Leetcode】479. Largest Palindrome Product
Deep Learning Fundamentals - Numpy-based Recurrent Neural Network (RNN) implementation and backpropagation training
尚硅谷MySQL学习笔记
伸展树的特性及实现
20220725资料更新
[Camp Experience Post] 2022 Cybersecurity Summer Camp
Thymeleaf简介
Docker搭建Mysql主从复制
numpy.where
ES中SQL查询详解
在linux下MySQL的常用操作命令
JAX-based activation function, softmax function and cross entropy function
【ACWing】406. 放置机器人
Win10安装DBeaver连接MySQL8、导入和导出数据库详细教程
如何进行数据库备份
字节跳动面试官:请你实现一个大文件上传和断点续传
Chrome书签插件,让你实现高效整理
color transparency parameter
ansible模块--copy模块