☰ All problems

Climbing Stairs

A charity stair-climb takes place in a stadium stairwell with n steps. With each stride a climber goes up either one or two steps, and the organizers want to know how many different stride patterns lead from the ground to exactly the top step.

Return the number of distinct sequences of one-step and two-step strides that add up to n. Two sequences count as different when they differ at any position, so 1 + 2 and 2 + 1 are both counted.

Example 1
Input: n = 4
Output: 5

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

Example 2
Input: n = 6
Output: 13
Example 3
Input: n = 1
Output: 1

Explanation: A single one-step stride is the only option.

Constraints

  • n is between 1 and 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