Climbing Stairs

Easy

You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Examples

InputOutput
n = 22
n = 33

Python Solution

def climb_stairs(n: int) -> int:
    if n <= 2:
        return n
    a, b = 1, 2
    for _ in range(3, n + 1):
        a, b = b, a + b
    return b

JavaScript Solution

function climbStairs(n) {
  if (n <= 2) return n;
  let a = 1, b = 2;
  for (let i = 3; i <= n; i++) {
    [a, b] = [b, a + b];
  }
  return b;
}

Step-by-Step Explanation

  1. Same recurrence as Fibonacci: ways(n) = ways(n-1) + ways(n-2).
  2. Use iterative DP with two variables to avoid recursion.

Complexity Analysis

TimeO(n)
SpaceO(1)

Tags

MathDynamic Programming

Related Problems

All Problems