[WIP] LeetCode 322. Coin Change

    科技2024-05-31  71

    题目:

    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.

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

     

    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

    Example 4:

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

    Example 5:

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

     

    Constraints:

    1 <= coins.length <= 121 <= coins[i] <= 231 - 10 <= amount <= 104

    主要的坑:dp数组长度为amount + 1,初始化dp数组不能用Integer.MAX_VALUE否则+1会overflow出错,需要在遍历coin的时候先check coin的面值是否大于当前amount。

    Runtime: 10 ms, faster than 95.92% of Java online submissions for Coin Change.

    Memory Usage: 38.5 MB, less than 91.24% of Java online submissions for Coin Change.

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

     

    Processed: 0.011, SQL: 8