Leet322. 零錢兌換(Coin Change)

https://leetcode-cn.com/problems/coin-change/description/

public static int coinChange(int[] coins, int amount) 
    {
       //dp[amount]=min(dp[amount-coins[i]])+1
        if(amount==0)
        {
            return 0;
        }
        int dp[]=new int[amount+1];
        Arrays.fill(dp, Integer.MAX_VALUE-1);
        dp[0]=0;
        for(int i=1;i<=amount;i++)
        {
            for(int j=0;j<coins.length;j++)
            {
                if(i>=coins[j])
                {
                    dp[i]=Math.min(dp[i-coins[j]]+1, dp[i]);//用當前硬幣 不用當前硬幣
                    //System.out.println("dp"+i+"="+dp[i]);
                }
            }
        }
        if(dp[amount]==Integer.MAX_VALUE-1)//無法完成
        {
            return -1;
        }
        else
        {
            return dp[amount];
        }
    }

填充Integer.MAX_VALUE-1的目的是防止溢出

如輸入coins爲[2] amount爲3時

dp[0]爲0

dp[1]爲Integer.MAX_VALUE-1

dp[2]時min中爲Integer.MAX_VALUE與Integer.MAX_VALUE-1的對比 可以取得正確值

而填充時不-1就會出現錯誤

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章