CodingNodes / 1-D Dynamic Programming / Climbing Stairs System design Space play · ←→ step · R restart

Problem

A staircase has n steps. On each move you climb either 1 step or 2 steps.

Return how many different sequences of moves take you from the ground to the top step exactly.

Constraints

  • 1 ≤ n ≤ 45

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: One pass over steps 2 to n, with a single addition for each step.

Space: The dp array holds n + 1 counts.

The last move into step i was either a 1-step from i-1 or a 2-step from i-2, so dp[i] = dp[i-1] + dp[i-2]. Start with one way to be on the ground and one way to reach step 1.