322.CoinChange

Example 1:

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Example 3:

Input: coins = [1], amount = 0
Output: 0

Note:

You may assume that you have an infinite number of each kind of coin.

ans[i]表示凑齐钱数i时需要的最小零钱数目
和题目494类似,但是内层遍历要从小到大
public int coinChange(int[] coins, int amount) {
int[] ans = new int[amount + 1];
for (int i = 0; i < amount + 1; i++)
ans[i] = amount + 1;//注意,初始化的时候不能设成Integer.MAX_VALUE,后面要有ans[i-coins[j]]+1的操作,会溢出称为Integer.MIN_VALUE
ans[0] = 0;
for (int i = 0; i < coins.length; i++) {
for (int j = coins[i]; j <= amount; j++) {
ans[j] = Math.min(ans[j], ans[j - coins[i]] + 1);
}
}
return ans[amount] == (amount + 1) ? -1 : ans[amount];
}
posted @   MarkLeeBYR  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示