Brush title 37-- change convertible (power button)

69.  change exchange

Topic Link

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/coin-change

Title Description

Given the different denominations of coins coins and a total amount of amount. We can write a function to calculate the minimum number of coins needed to make up the total amount. If there is no combination can be composed of any of a total amount of 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 can think of each coin number is unlimited.

Key Technology

Dynamic Programming

Topic analysis

Analysis according to Example 1:

  1. Coin denomination are: 1,2,5, the total amount is 11, is now assumed that DP [i] is the sum of the number of coins when the optimal solution of i;
  2. Because there are three different denominations, so there are 11 required three methods are: 1 + dp [10]; 1 + dp [8]; 1 + dp [6];
  3. Thus converting the Optimal Solution 11 is three or more, respectively, an optimal solution, which is a minimum number of coins, i.e., dp [11] = Math.min (1 + dp [10], 1+ dp [8], 1 + dp [6])
  4. Derived state transition equation: dp [i] = Math.min (dp [i-coin] +1, dp [i-coin] +1, dp [i-coin] +1, ......)
  5. How many coin to compare how many times, coin depends on how many coins of different denominations are several.
  6. For dp [10], dp [8], dp [6] and then according to the above decomposition step.
/**
 * @param {number[]} coins
 * @param {number} amount
 * @return {number}
 */
var coinChange = function(coins, amount) {
    var dp = new Array(amount+1).fill(Infinity); 
    dp[0] = 0;
    for(let i=0;i<=amount;i++){
        for(let coin of coins){
            if(i - coin >= 0){
                dp[i] = Math.min(dp[i],dp[i-coin]+1);
            }
        }
    }
    return dp[amount] === Infinity ? -1 : dp[amount];
    
};

  

Guess you like

Origin www.cnblogs.com/liu-xin1995/p/12444790.html