☰ All problems

53. Climbing Stairs

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

Return how many different sequences of moves bring you from the bottom to exactly the top step.

Example 1
Input: n = 2
Output: 2

Explanation: Either two single steps (1 + 1) or one double step (2).

Example 2
Input: n = 3
Output: 3

Explanation: The sequences are 1 + 1 + 1, 1 + 2 and 2 + 1.

Example 3
Input: n = 5
Output: 8

Constraints

  • 1 <= n <= 45

Follow-up: Can you get it in O(log n) time? (Hint: the recurrence can be written as a 2×2 matrix power.)

💡 Hint 1

Think about the very last move. It was either a 1-step from step n - 1 or a 2-step from step n - 2.

💡 Hint 2

So ways(n) = ways(n - 1) + ways(n - 2). Computing this recursively without caching repeats a lot of work.

💡 Hint 3

You only ever need the previous two values, so two variables are enough.

/**
 * @param {number} n
 * @return {number}
 */
function climbStairs(n) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc