LeetCode--No.322--Coin Change

322. Coin Change

Medium

166272FavoriteShare

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

 

其实是很典型的dp题目,因为是可以根据之前的结果计算出下一步的值。
但是自己想起来这个过程的时候,意识到了,对于这个数组内不同的amount, 那么amount - coins[i] 的结果该如何存储,以及如何返回正确的值,看起来很复杂,就懒了,没有再想下去。

可能最根本的地方在于,一开始没有觉得可以建一个数组,存从0到amount的所有情况,所以就想得更复杂,但其实如果更深入进detail的话,是有可能做出来的。而且不能懒, 返回0和返回-1这种不同的情况,也可以好好设计一下。而且将min设为Integer_max_value的地方也有点巧妙。
第一步也没想出来,就是,最终的结果,取决于之前的减去coins数组中每个值的结果中最小的结果+1. 这一步也很关键。
 

class Solution {
    int res = 0;
    public int coinChange(int[] coins, int amount) {
        if(amount < 1)  return 0;
        return coinChangeHelper(coins, amount, new int[amount]);
    }
    private int coinChangeHelper(int[] coins, int rem, int[] count){
        if (rem < 0)    return -1;
        if (rem == 0)   return 0;
        if (count[rem - 1] != 0)    return count[rem - 1];
        int min = Integer.MAX_VALUE;
        for(int coin : coins){
            int res = coinChangeHelper(coins, rem - coin, count);
            if (res >= 0)
                min = Math.min(min, res + 1);
        }
        count[rem - 1] = (min == Integer.MAX_VALUE) ? -1 : min;
        return count[rem - 1];
    }
}

上面这个是自顶向下的方法 Top Bottom. 从最大的数起开始调用之前的函数, 然后设定好结束条件, 每次更新数组的值. 

下面这个是Bottom Up 感觉这个更make sense, 也没什么初始条件,就是从数组的第一个值开始,一个一个更新。

class Solution {
    public int coinChange(int[] coins, int amount) {
        int max = amount + 1;
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, max);
        dp[0] = 0;
        for(int i = 1; i <= amount; i++){
            for(int coin: coins) {
                if (coin <= i)
                    dp[i] = Math.min(dp[i], dp[i - coin] + 1);
            }

        }
        return dp[amount] > amount ? -1 : dp[amount];
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值