Climbing Stairs

Easy1-D dynamic programming

A staircase has n steps. Each move climbs either 1 step or 2 steps.

Return how many different sequences of moves take you from the bottom to the top.

Examples

Example 1
Input:  n = 3
Output: 3

1+1+1, 1+2 and 2+1.

Example 2
Input:  n = 4
Output: 5

1+1+1+1, 1+1+2, 1+2+1, 2+1+1 and 2+2.

Constraints

  • 1 ≤ n ≤ 45

Stuck?

Hint 1

Your last move was either 1 step or 2. So the ways to reach step n are the ways to reach n - 1 plus the ways to reach n - 2.

Hint 2

Plain recursion repeats the same work and runs out of time long before n = 45. Keep only the last two counts as you climb.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 8 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur