322. Coin Change

Difficulty:
Related Topics:
Similar Questions:

    Problem

    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.

    Note: You may assume that you have an infinite number of each kind of coin.

    Credits:

    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

    Solution 1

    /**
     * @param {number[]} coins
     * @param {number} amount
     * @return {number}
     */
    var coinChange = function(coins, amount) {
      var dp = [];
      return coin(coins, amount, dp);
    };
    
    var coin = function (coins, amount, dp) {
      if (dp[amount - 1] !== undefined) return dp[amount - 1];
      if (amount < 0) return -1;
      if (amount === 0) return 0;
    
      var count = Number.MAX_SAFE_INTEGER;
      var tmp = 0;
    
      for (var i = 0; i < coins.length; i++) {
        tmp = coin(coins, amount - coins[i], dp);
        if (tmp !== -1) count = Math.min(count, tmp + 1);
      }
    
      dp[amount - 1] = count === Number.MAX_SAFE_INTEGER ? -1 : count;
    
      return dp[amount - 1];
    };
    

    Explain:

    动态规划,从上到下。

    Complexity:

    Solution 2

    /**
     * @param {number[]} coins
     * @param {number} amount
     * @return {number}
     */
    var coinChange = function(coins, amount) {
      var dp = Array(amount + 1).fill(amount + 1);
    
      if (amount < 0) return -1;
      if (amount === 0) return 0;
    
      dp[0] = 0;
    
      for (var i = 1; i <= amount; i++) {
        for (var j = 0; j < coins.length; j++) {
          if (i >= coins[j]) {
            dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
          }
        }
      }
    
      return dp[amount] > amount ? -1 : dp[amount];
    };
    

    Explain:

    动态规划,从下到上。

    Complexity: