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.數組

Example 1:數據結構

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

Example 2:ide

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

 [暴力解法]:oop

時間分析:優化

空間分析:spa

 [優化後]:debug

時間分析:code

空間分析:orm

[奇葩輸出條件]:

[奇葩corner case]:

dp數組運行了以後纔有正常值,因此須要用arrays.fill初始化爲奇葩值

[思惟問題]:

[英文數據結構或算法,爲何不用別的數據結構或算法]:

Math.min(dp[目標值], dp[目標值 - 當前值] + 1);

[一句話思路]:

[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):

[畫圖]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分鐘肉眼debug的結果]:

[總結]:

記得初始化

[複雜度]:Time complexity: O(n2) Space complexity: O(n)

[算法思想:迭代/遞歸/分治/貪心]:

[關鍵模板化代碼]:

[其餘解法]:

 

class Solution {
    public int coinChange(int[] coins, int amount) {
        //corner case
      if (coins == null || coins.length <= 0 || amount <= 0) return -1;
      
      //initialization: dp[] and fill, and the first num
      int[] dp = new int[amount + 1];
      Arrays.fill(dp, amount + 1);
      dp[0] = 0;
      
      //for loop for each coins, each amount
      for (int j = 0; j < coins.length; j++) {
        for (int i = 0; i <= amount; i++) {
          if (i - coins[j] >= 0)
            dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
        }
      }
      
      //return if dp[] is normal value, or just -1
      return dp[amount] > amount ? -1 : dp[amount];
    }
}
View Code

 

 

 

[Follow Up]:

[LC給出的題目變變變]:

 [代碼風格] :

 [是否頭一次寫此類driver funcion的代碼] :

 [潛臺詞] :

相關文章
相關標籤/搜索