(Js) Leetcode 322. Change Exchange

topic:

Given coins of different denominations and a total amount. Write a function to calculate the minimum number of coins required to make up the total amount. If no coin combination can make up the total amount, return -1.

You can think that the number of each coin is unlimited.

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
Example 3:

Input: coins = [1], amount = 0
Output: 0
Example 4:

Input: coins = [1], amount = 1
Output: 1
Example 5:

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

prompt:

1 <= coins.length <= 12
1 <= coins[i] <= 231 - 1
0 <= amount <= 104

Ideas:

Dynamic programming

Code:

/**
 * @param {number[]} coins
 * @param {number} amount
 * @return {number}
 */
var coinChange = function(coins, amount) {
    // 数组大小为 amount + 1
    let dp = new Array( amount + 1 ).fill( Infinity );
    dp[0] = 0;
    // 外层 for 循环在遍历所有状态的所有取值
    for (let i = 1; i <= amount; i++) {
        // 内层 for 循环在求所有选择的最小值
        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];

};

operation result:

Guess you like

Origin blog.csdn.net/M_Eve/article/details/113532362