leetcode 322. Coin Change(交换硬币)

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.

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

给出一个amount,给出几种coin,无限枚数,问最少能用几枚硬币组成amount

思路:

dp
倒推,用组成(amount-当前coin)的硬币枚数+(当前coin)1枚
即dp[amount - coin] + 1

遍历所有硬币,比如amount= 11
第一行表示coin=1参与的时候最少的硬币数,第二行表示在coin=2可以参与(也可以不参与,只有1)的情况下最少的枚数。同理coin=5。
amount: 0 1 2 3 4 5 6 7 8 9 10 11
1              0 1 2 3 4 5 6 7 8 9 10 11
2              0
5
(coin)

coin是2,amount=1的时候,amount-coin<0,所以对于小于coin本身的amount,直接跳过,保留上次的结果。
到amount=2,dp[2][amount - coin]+1 = dp[2][0] + 1,即用一枚2硬币本身就能构成amount=2
取min(dp[1][amount], dp[2][amount - coin] + 1)

进一步压缩dp数组到一维,即在上一枚硬币的基础上更新

*注意硬币无法组成amount时是∞,因此在∞的时候返回-1
*硬币无法组成amount,即dp[i - coin] = ∞时,不需要更新dp,继续保持无法组成的状态

    //7ms
    public int coinChange(int[] coins, int amount) {
        if (coins == null || coins.length == 0 || amount < 0) {
            return -1;
        }
        
        int[] dp = new int[amount + 1];        
        Arrays.fill(dp, Integer.MAX_VALUE);
        
        dp[0] = 0;
        
        for (int coin : coins) {
            for (int i = coin; i <= amount; i++) {
                if (dp[i - coin] != Integer.MAX_VALUE) {
                    dp[i] = Math.min(dp[i], dp[i - coin] + 1);
                }
            }
        }
        
        if (dp[amount] == Integer.MAX_VALUE) {
            return -1;
        }
        return dp[amount];
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值