[LeetCode]Coin Change

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.spa

Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)code

Example 2:
coins = [2], amount = 3
return -1.it

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

分析

典型的DP問題。注意這裏的硬幣是能夠無限使用的,另外注意下沒法兌換返回-1的處理。
不少人首先想到的是Greedy,即老是取最大的硬幣,不夠再取小的,這種方法獲得的結果是不能保證最小硬幣數量的, 好比輸入是[1, 3, 5, 6], 8, Greedy獲得結果是3(6 + 1 + 1),而正確結果是2(3 + 5)function

這道題要求是返回硬幣個數,顯然Follow up能夠是在最少硬幣的狀況下,返回具體的硬幣值class

我能想到的比較直接的方法就是用一個map對於每一個能夠組合的amount用一個List存對應的硬幣組合,而後一樣是DP的方法找到最小硬幣組合,更新組合。List

複雜度

time: O(n*m), space: O(n), n表示amount,m表示硬幣個數。map

代碼

public class Solution {
    public int coinChange(int[] coins, int amount) {
        // 無效輸入的處理
        if (amount == 0)
            return 0;
        if (coins == null || coins.length == 0)
            return -1;
            
        int[] dp = new int[amount + 1];
        for (int i = 1; i <= amount; i++) {
            int min = Integer.MAX_VALUE;
            for (int j = 0; j < coins.length; j++) {
                if (i >= coins[j] && dp[i - coins[j]] != -1)
                    min = Math.min(min, dp[i - coins[j]] + 1);
            }
            
            // 根據min的值判斷是否能兌換
            dp[i] = min == Integer.MAX_VALUE ? -1 : min;
        }
        return dp[amount];
    }
}
相關文章
相關標籤/搜索