LeetCode(322):零钱兑换 I II Coin Change I II (Java)

2019.7.26 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

两道零钱兑换都是经典的完全背包问题,第一道题要求求出最少所需的银币数,第二道题要求求出可能的组合数。

动态规划是解决背包问题的通法,先对硬币面值排序,然后上DP大法即可。

第一题,dp[sum]表示在加入面值为value的硬币之后获得总额为sum所需要的最少硬币数,dp[sum] = Math.min(dp[sum], dp[sum - value] + 1);表示每次可以将dp[sum - value]所需的硬币加上一张面值为value的硬币凑成sum的总额。

当然,按照人正常的逻辑思路去思考,第一题也可以用贪心+剪枝DFS来做。每次按硬币面值按照从大到小的顺序取,对于amount的总额,第一次取完value[i]面值后,递归对amount-value[i]继续取。对当面面值使用次数超过最小次数的枝干进行剪枝即可。

第二题和第一题类似,dp[sum]表示凑成总金额sum的硬币组合数,dp[sum] += dp[sum - coin];表示将sum-coin的组合数加上面值为coin的硬币。最外层遍历所有的面值。


传送门:零钱兑换

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回-1。

示例 1:
输入: coins = [1, 2, 5], amount = 11
输出: 3 
解释: 11 = 5 + 5 + 1

示例 2:
输入: coins = [2], amount = 3
输出: -1

说明:
你可以认为每种硬币的数量是无限的。


import java.util.Arrays;

/**
 *
 * You are given coins of different denominations and a total amount of money amount.
 * Write a function to compute the fewest number of coins that you need to make up that amount.
 * If that amount of money cannot be made up by any combination of the coins, return -1.
 * 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
 *
 */

public class CoinChange {
   

    //动态规划
    public int coinChange(int[] coins, int amount) {
   
        Arrays.sort(coins);
        int[] dp = new int[amount + 
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值