Question

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 = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2:

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

Thinking:

  • Method 1:DP
      class Solution {
          public int coinChange(int[] coins, int amount) {
              int[] dp = new int[amount + 1];
              for(int i = 1; i < amount + 1; i++)
                  dp[i] = -1;
              for(int c : coins)
                  if(c < amount + 1)
                      dp[c] = 1;
              for(int i = 1; i <= amount; i++){
                  if(dp[i] != -1) continue;
                  saveMin(dp, coins, i);
              }
              return dp[amount];
          }
          private void saveMin(int[] dp, int[] coins, int index){
              int min = Integer.MAX_VALUE;
              for(int c : coins){
                  if(index - c >= 0 && dp[index - c] != -1){
                      min = Math.min(min, dp[index - c]);
                  }
              }
              dp[index] = min == Integer.MAX_VALUE ? -1 : min + 1;
          }
      }
    

Second Time

  • Method 1: dp AC 83.88%
      class Solution {
          public int coinChange(int[] coins, int amount) {
              int len = coins.length;
              int[] dp = new int[amount + 1];
              Arrays.fill(dp, Integer.MAX_VALUE >> 1);
              dp[0] = 0;
              for(int coin : coins){
                  if(coin <= amount)
                      dp[coin] = 1;
              }
              for(int i = 1; i <= amount; i++){
                  if(dp[i] == 1) continue;
                  for(int coin : coins){
                      dp[i] = Math.min(i - coin >= 0 ? dp[i - coin] + 1: Integer.MAX_VALUE >> 1, dp[i]);
                  }
              }
              return dp[amount] == Integer.MAX_VALUE >> 1 ? -1: dp[amount];
          }
      }