Ways to Pay the Toll

Medium · 2-D & String DP · about 20 min

A toll machine takes coins of the values in coins (all different, unlimited supply of each). Return how many different combinations of coins add up to exactly amount.

Order does not matter: 1 + 2 and 2 + 1 are the same combination. An amount of 0 has exactly one combination (no coins). Because the count can be huge, return it modulo 1,000,000,007.

  • 0 <= len(coins) <= 50, coin values from 1 to 5000, all different.
  • 0 <= amount <= 5000.

Examples:

count_payment_ways([1, 2, 5], 5) → 4 (5, 2+2+1, 2+1+1+1, 1+1+1+1+1)

count_payment_ways([2], 3) → 0

Hints

  • ways[a] = number of combinations that make amount a. ways[0] = 1.
  • Loop over the coin types first and the amounts second. That fixes the order in which coins are added, so each combination is counted once.
  • A coin can be used again, so the amounts go from low to high. Take the modulo after every addition.

Learn the pattern first: the 2-D & String DP lesson.

More 2-D & String DP problems