Climbing Stairs

25 min · climbStairs()

A staircase looks harmless until you count every route up it.

You face n steps. Each move climbs either 1 step or 2 steps. Return the number of distinct move sequences that land exactly on the top.

The order of the moves matters: climbing 1, 2 and climbing 2, 1 are two different ways to reach step 3. A move that passes the top doesn't count.

Constraints

  • 1 <= n <= 45
  • The answer fits in a signed 32-bit integer.

Hints

Look at the final move

Every valid route ends with either a 1-step move or a 2-step move. Where could you have been just before each of those moves?

Reuse smaller answers

If ways[i] counts routes to step i, then every route to i comes from step i - 1 or step i - 2. Add those two counts.

Keep only what moves forward

Computing the next count needs only the previous two counts. You don't need to keep the full history.

Follow-up

If each move could climb 1, 2, or 3 steps, how would the recurrence and the amount of stored history change?

Visible cases

Examples

Example 1

ready
Input
n = 2
Expected
2
Why
the routes are 1+1 and 2

Example 2

ready
Input
n = 3
Expected
3
Why
1+1+1, 1+2, and 2+1 reach the top

Example 3

ready
Input
n = 1
Expected
1
Why
one 1-step move is the only route

Interview signal

Asked at

AmazonGoogleAdobe
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite