Menu
CoddyTech

Coin Change

中等动态规划python iconjava iconcpp iconc iconjs icon+10

你会得到一个包含不同硬币面值的列表 coins 和一个目标 amount。每种面值的硬币都可以使用任意次。请返回面值之和恰好等于 amount 的最少硬币数;如果无法凑出该金额,则返回 -1。金额为 0 时需要 0 枚硬币。

函数

coinChange(coins: integer-array, amount: integer) → integer
coinsinteger-array
不同面值的硬币,每种都可以使用任意次数
amountinteger
应付总额,准确无误
返回值integer
所需硬币数最少;如果无法凑出该金额,则返回 -1

约束条件

  • 1 ≤ coins.length ≤ 12
  • 1 ≤ coins[i] ≤ 104
  • 0 ≤ amount ≤ 104
  • 所有硬币的面值都不同。

示例

输入
coins = [2, 5, 10]amount = 27
输出
4
解释
用 4 枚硬币组成 10 + 10 + 5 + 2,结果是 27。用 3 枚硬币无法组成:27 是奇数,所以必须恰好用 1 枚 5,另外 2 枚最多只能组成 20,不够 22。
challenge icon

进阶

你能计算出有多少种不同的硬币组合可以凑成 amount,而不是找出所需硬币数量最少的组合吗?

重置代码
def coinChange(coins, amount):
    # 在这里编写代码

测试 #1

测试 #2

测试 #3

参数

coins = [2, 5, 10]
amount = 27

预期输出

4