1. 程式人生 > >LeetCode322. 零錢兌換

LeetCode322. 零錢兌換

題目

給定不同面額的硬幣 coins 和一個總金額 amount。編寫一個函式來計算可以湊成總金額所需的最少的硬幣個數。如果沒有任何一種硬幣組合能組成總金額,返回 -1

分析

用動態規劃,自底向上的計算1,2,3,45,……amount的最小硬幣個數。

dp[i]  =  min(dp[i] , dp[i-coins[j]]+1)

程式碼

class Solution {
    public int coinChange(int[] coins, int amount) {
        if (amount == 0) return 0;
        
        int[] dp = new int[amount + 1];

        for (int i = 1; i <= amount; i++) {
            dp[i] = Integer.MAX_VALUE;

            for(int c : coins){
                if (i >= c && dp[i-c] != Integer.MAX_VALUE){
                    dp[i] = Math.min(dp[i], dp[i-c]+1);
                }
            }
        }

        if (dp[amount]<Integer.MAX_VALUE && dp[amount] > 0)return dp[amount];
        else  return -1;
    }
}