Problem 583145 · medium · Phase 05 Advanced Algorithms & Graphs

Stamp Combinations

dynamic programming · 1-D dp · unordered combinations · modular arithmetic

A post office sells stamps in the denominations values (distinct positive integers, unlimited supply). Return how many different multisets of stamps add up exactly to total, modulo 10**9 + 7. Order does not matter: using a 1 then a 2 is the same as a 2 then a 1. A total of 0 has exactly one way (no stamps).

Examples

Input:  total = 5, values = [1, 2]
Output: 3
Explanation: {1,1,1,1,1}, {1,1,1,2}, {1,2,2}.

Input:  total = 4, values = [2, 3]
Output: 1

Constraints

  • 0 <= total <= 10**4
  • 1 <= len(values) <= 20, 1 <= values[i] <= 10**4, distinct
  • Target complexity: O(total * len(values)) time.

Goals

  • Count unordered multisets that reach a total by processing one denomination at a time
  • See why the loop order differs from the ordered-sequence count
Starting Python…