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];
    }
}

猜你喜欢

转载自blog.csdn.net/sophia_tone2w/article/details/90137369
今日推荐