← 中文资源

简体中文版本

零钱兑换 DP 求最少硬币

自底向上 DP:dp[x] 记凑出金额 x 的最少枚数,choice 表逆推具体面额;面额全为偶数时奇数金额返回 -1,贪心在此例会多花一枚。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

5
[12, 5, 5, 5, 1]
-1

实现说明

零钱兑换 DP 求最少硬币可以归结为函数 fewest_coins、which_coins。 这个示例中仅有的重复出现在 for coin in coins 里。

使用要点

  • 调用方只需要 fewest_coins——其余都是内部实现。

常见问题

需要安装第三方包吗?

不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 文件在加载时定义 fewest_coins、which_coins。

入口签名:def fewest_coins(amount, coins)

核心语句

def fewest_coins(amount, coins):
    # dp[x] = 凑出金额 x 的最少硬币数;dp[0] = 0
    dp = [0] + [float('inf')] * amount
    for coin in coins:
        for x in range(coin, amount + 1):
            if dp[x - coin] + 1 < dp[x]:
                dp[x] = dp[x - coin] + 1
    return dp[amount] if dp[amount] != float('inf') else -1

代码示例

def fewest_coins(amount, coins):
    # dp[x] = 凑出金额 x 的最少硬币数;dp[0] = 0
    dp = [0] + [float('inf')] * amount
    for coin in coins:
        for x in range(coin, amount + 1):
            if dp[x - coin] + 1 < dp[x]:
                dp[x] = dp[x - coin] + 1
    return dp[amount] if dp[amount] != float('inf') else -1


def which_coins(amount, coins):
    # 回溯:choice[x] 记下达成 dp[x] 的那枚面额,从总额逆推
    dp = [0] + [float('inf')] * amount
    choice = [None] * (amount + 1)
    for coin in coins:
        for x in range(coin, amount + 1):
            if dp[x - coin] + 1 < dp[x]:
                dp[x] = dp[x - coin] + 1
                choice[x] = coin
    picked, x = [], amount
    while x:
        picked.append(choice[x])
        x -= choice[x]
    return sorted(picked, reverse=True)


coins = [1, 5, 12, 19]
print(fewest_coins(28, coins))
print(which_coins(28, coins))
print(fewest_coins(7, [2, 4]))  # 全是偶数面额,奇数金额凑不出