322.Coin-Change

322. Coin Change

题目地址

https://leetcode.com/problems/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 = [1, 2, 5], amount = 11
Output: 3 
Explanation: 11 = 5 + 5 + 1

Example 2:
Input: coins = [2], amount = 3
Output: -1
Note:
You may assume that you have an infinite number of each kind of coin.

代码

Approach #2 DFS

Complexity Analysis

  • Time complexity : O(S×n)

  • Space complexity : O(S)

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

  private int dfs(int[] coins, int rem, int[] memo) {
    if (rem < 0)     return -1;
    if (rem == 0)    return 0;
    if (memo[rem] != 0)    return memo[rem];
    int min = Integer.MAX_VALUE;

    for (int coin : coins) {
      int res = dfs(coins, rem - coin, memo);
      if (res >= 0 && res < min) {
        min = 1 + res;
      }
    }
    memo[rem] = (min == Integer.MAX_VALUE) ? -1 : min;
    return memo[rem];
  }
}

Approach #3 Dynamic programming - Bottom up

Complexity Analysis

  • Time complexity : O(Sn). On each step the algorithm finds the next F(i) in n iterations, where 1≤ iS. Therefore in total the iterations are Sn.

  • Space complexity : O(S). We use extra space for the memoization table.

class Solution {
  public int coinChange(int[] coins, int amount) {
    int max = amount + 1;
    int[] dp = new int[amount + 1];
    Arrays.fill(dp, max);    
    dp[0] = 0;
    for (int i = 1; i <= amount; i++) {
      for (int j = 0; j < coins.length; j++) {
        if (coins[j] <= i) {
          dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
        }
      }
    }

    return dp[amount] > amount ? -1 : dp[amount];
  }
}

Approach #1 (Brute force) [Time Limit Exceeded]

public class Solution {

  public int coinChange(int[] coins, int amount) {
    return coinChange(0, coins, amount);
  }

  private int coinChange(int idxCoin, int[] coins, int amount) {
    if (amount == 0)
      return 0;
    if (idxCoin < coins.length && amount > 0) {
      int maxVal = amount/coins[idxCoin];
      int minCost = Integer.MAX_VALUE;
      for (int x = 0; x <= maxVal; x++) {
        if (amount >= x * coins[idxCoin]) {
          int res = coinChange(idxCoin + 1, coins, amount - x * coins[idxCoin]);
          if (res != -1)
            minCost = Math.min(minCost, res + x);
        }
      }
      return (minCost == Integer.MAX_VALUE)? -1: minCost;
    }
    return -1;
  }
}

// Time Limit Exceeded

Last updated