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

Example 1:函數

Input: coins = [1, 2, 5], amount = 11
Output: 3 
Explanation: 11 = 5 + 5 + 1

Example 2:code

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

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

難度:mediumio

題目:給定不一樣面值的硬幣和一總金額。寫一個函數來計算你須要的最少的硬幣數量來構成這個總金額。若是這筆錢不能用硬幣的任何組合來構成,則返回-1。ast

思路:DP
total[i]表示這個金額最少須要多少硬幣組成。
total[amount] = Math.min(total[amount - coins[i]] + 1) (total[amount - coins[i]] > 0)
(total[amount - coins[i]] = 0) 意味着不可達。function

Runtime: 13 ms, faster than 97.29% of Java online submissions for Coin Change.
Memory Usage: 38 MB, less than 42.39% of Java online submissions for Coin Change.class

class Solution {
    public int coinChange(int[] coins, int amount) {
        if (null == coins || coins.length < 1 || amount <= 0) {
            return 0;
        }
        int[] total = new int[amount + 1];
        Arrays.sort(coins);
        for (int i = 0; i < coins.length && coins[i] < total.length; i++) {
            total[coins[i]] = 1;
        }
        
        for (int i = coins[0]; i <= amount; i++) {
            if (total[i] > 0) {
                continue;
            }
            total[i] = amount + 1;
            for (int j = 0; j < coins.length && i - coins[j] >= 0; j++) {
                if (total[i - coins[j]] > 0) {
                    total[i] = Math.min(total[i - coins[j]] + 1, total[i]);
                }
            }
        }
        
        return total[amount] > amount || total[amount] <= 0 ? -1 : total[amount];
    }
}
相關文章
相關標籤/搜索