Coin Change DP Finds Fewest Coins

Bottom-up DP computes the fewest coins per amount and a choice table backtracks the exact denominations, returning -1 when the amount is unreachable.

PythonData Integrity

Code

pythonsnippet
30 lines
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]))  # 全是偶数面额,奇数金额凑不出

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Coin Change DP Finds Fewest Coins, line by line

Structurally, expect the functions fewest_coins and which_coins and nothing else.

The loop for coin in coins is the only repeated construct.

Watch out for

  • The dependency count is zero — the platform supplies all the APIs.

Using it

Entry signature: def fewest_coins(amount, coins)

Import fewest_coins from the file and call it — the rest of the code is implementation detail.

Key statements

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

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `fewest_coins`, `which_coins` at load time.