Count the ways with the coin loop outside
Order ignored is a combination, order counted is an ordering
Here are all the ways to make 6 cents from coins of 1, 3 and 4:
| A combination, order ignored | Its orderings, order counted | How many |
|---|---|---|
| 1+1+1+1+1+1 | 1+1+1+1+1+1 | 1 |
| 3+1+1+1 | 3+1+1+1, 1+3+1+1, 1+1+3+1, 1+1+1+3 | 4 |
| 3+3 | 3+3 | 1 |
| 4+1+1 | 4+1+1, 1+4+1, 1+1+4 | 3 |
| 4 combinations | 9 orderings | 9 |
The problem asks for combinations. The order of your two loops decides which one you count. Here is the version with the coins outside:
def count_ways(amount: float, coins: list[float]) -> int:
"""Combinations that make amount exactly, order ignored."""
target = round(amount * 100)
values = sorted({round(c * 100) for c in coins})
# one way to make 0: no coins
ways = [1] + [0] * target
# coins outside
for v in values:
# amounts inside
for t in range(v, target + 1):
ways[t] += ways[t - v]
return ways[target]
print(count_ways(0.06, [0.01, 0.03, 0.04]))
4
ways[t] is the number of ways to make t cents. Each coin makes one pass over the amounts, from its own value up, and adds ways[t - v] to ways[t]. That counts the 4 combinations. Swap the two loops, with the amounts outside and every coin that fits inside, and the same addition counts the 9 orderings.
The table is the same shape as for the fewest coins. Only the rules change:
| Fewest coins | Number of ways | |
|---|---|---|
| a cell holds | the fewest coins that make | how many combinations make |
| start | best[0] = 0, every other cell | ways[0] = 1, every other cell 0 |
| combine | the min over coins, plus 1 | the sum over coins |
| loop order | either one | coins outside |
| unreachable | -1 | 0 |
ways[0] = 1 is not a hack. There is exactly one way to make 0 cents: take no coins. Every count is built on it, because a coin worth exactly adds ways[0] to ways[t]. Start it at 0 and every count stays 0. It's also why count_ways(0.0, [0.25]) is 1.
In the editor, write orderings(target, values), in cents: how many sequences of coins make target, with order counted. Put the amount loop outside, and the coins that fit inside it.