829. Count the ways to climb a staircase with allowed step sizes
Counting paths is the simplest dynamic programming pattern, and it is the same idea behind counting sequences in a lattice or a decoding graph.
Write climb_ways(n, steps). You start at stair 0 and want to reach stair n exactly. Each move climbs one of the sizes in the list steps (all positive integers, no duplicates). The order of moves matters. Return the number of distinct move sequences that land exactly on stair n. climb_ways(0, steps) is 1 (the empty sequence).
def climb_ways(n, steps)Example 1
Input: climb_ways(4, [1, 2])
Output: 5
Example 2
Input: climb_ways(3, [2])
Output: 0
Example 3
Input: n = 0, steps = [1, 2]
Output: 1
Constraints
- 0 <= n <= 10,000
- 1 <=
len(steps)<= 10
Hint 1
Define ways[0] = 1.
Hint 2
Sum over the last move.
Hint 3
Skip step sizes larger than the current stair.
Common mistakes
- Setting
ways[0]to 0, which makes every answer 0. - Recursing without memoization, which is exponential.
- Counting combinations instead of ordered sequences.
Understand the idea
Bottom-up dynamic programming stores the answer for every smaller stair so each one is computed once. For n = 4 and steps [1, 2] the table is 1, 1, 2, 3, 5. Time is O(n x k) for k step sizes, and memory can drop to O(max step) by keeping only the last few entries.