322. Coin Change

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:

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

  • Example 2:

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

  • 題目大意:給定一個硬幣數組,給定amount,問使用硬幣數組中的硬幣,找出能組成amount的最少的硬幣數。

  • 思路:dp.dp[i]表示組成i元錢需要的最少的硬幣的個數。

  • 代碼

    package DP;
    
    import java.util.Arrays;
    
    /**
    * @author OovEver
    * 2018/1/6 14:41
    */
    public class LeetCode322 {
      public static int coinChange(int[] coins, int amount) {
          if (amount == 0) {
              return 0;
          }
          for (int i=0;i<coins.length;i++) {
              if (coins[i] == amount) {
                  return 1;
              }
          }
    //        dp[i]表示組成i元錢需要的最少的硬幣的個數
          int[] dp = new int[amount + 1];
          for(int i=0;i<coins.length;i++) {
              if (coins[i] <= amount) {
                  dp[coins[i]] = 1;
              }
          }
          for(int i=0;i<coins.length;i++) {
              for(int j=coins[i];j<=amount;j++) {
                  if (dp[j] != 0 && dp[j - coins[i]] != 0) {
                      dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1);
                  } else if (dp[j - coins[i]] != 0) {
                      dp[j] = dp[j - coins[i]] + 1;
                  }
              }
          }
          if (dp[amount] == 0) {
              return -1;
          }
          return dp[amount];
      }
    
    }
    
發佈了207 篇原創文章 · 獲贊 69 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章