Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

322. 零钱兑换 #80

Open
webVueBlog opened this issue Sep 5, 2022 · 0 comments
Open

322. 零钱兑换 #80

webVueBlog opened this issue Sep 5, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

322. 零钱兑换

Description

Difficulty: 中等

Related Topics: 广度优先搜索, 数组, 动态规划

给你一个整数数组 coins ,表示不同面额的硬币;以及一个整数 amount ,表示总金额。

计算并返回可以凑成总金额所需的 最少的硬币个数 。如果没有任何一种硬币组合能组成总金额,返回 -1

你可以认为每种硬币的数量是无限的。

示例 1:

输入:coins = [1, 2, 5], amount = 11
输出:3 
解释:11 = 5 + 5 + 1

示例 2:

输入:coins = [2], amount = 3
输出:-1

示例 3:

输入:coins = [1], amount = 0
输出:0

提示:

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

Solution

Language: JavaScript

/**
 * @param {number[]} coins
 * @param {number} amount
 * @return {number}
 */
/**
[1, 2, 5] 11
dp[11] 总金额为11的 硬币数量

dp[11] = dp[6] + (5) / dp[9] + (2) / dp[10] + (1)
 */
var coinChange = function(coins, amount) {
    const dp = new Array(amount + 1).fill(Infinity)
    dp[0] = 0
    // 从1到11
    for (let i = 1; i <= amount; i++) {
        // dp[1]到dp[11]求
        for (let coin of coins) {
            if (i - coin < 0) continue
            dp[i] = Math.min(dp[i], dp[i-coin]+1)
        }
    }
    return dp[amount] === Infinity ? -1 : dp[amount]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant