Climbing Stairs easy

Description

You are climbing a staircase with n steps. Each move, you can climb either 1 step or 2 steps. How many distinct ways are there to reach the top?

Examples

> Case 1:
    Input:  n = 2
    Output: 2          # (1+1) or (2)
 
> Case 2:
    Input:  n = 3
    Output: 3          # (1+1+1), (1+2), (2+1)
 
> Case 3:
    Input:  n = 4
    Output: 5          # (1+1+1+1), (1+1+2), (1+2+1), (2+1+1), (2+2)

Constraints

  • 1 <= n <= 45

Intuition

Apply the three-question recipe:

  1. Base case: at n = 0 you’ve reached the top — exactly 1 way (the empty sequence of moves). At n = 1, also 1 way (a single 1-step).
  2. Recursive case: the last step is either a 1 or a 2. So ways(n) = ways(n - 1) + ways(n - 2).
  3. Combine: add.

That recurrence is Fibonacci in disguise — ways(n) = fib(n + 1).

Naive ways(5) — exponential blowup
w(5)= 8w(4)= 5w(3)= 3w(2)= 2w(1)= 1w(0)= 1w(1)= 1w(2)= 2w(1)= 1w(0)= 1w(3)= 3w(2)= 2w(1)= 1w(0)= 1w(1)= 1
recursive call    base case15 total calls

Just like naive Fibonacci, this branches twice per call — O(2^n). We’ll fix it with memoization or a bottom-up loop.

Approach 1: Naive recursion (don’t actually submit this)

Time O(2^n), space O(n) for the call stack. n = 45 would take ages — TLE on any judge.

Approach 2: Memoized recursion (linear)

Time O(n), space O(n).

Approach 3: Bottom-up with O(1) space

We only need the last two values at any moment — no array needed.

Time O(n), space O(1) — best of both worlds.

Climbing Stairs is the Hello World of dynamic programming. The exact same recurrence appears in: tile-laying problems, decode-ways, count-paths-in-a-grid, and Fibonacci itself. Recognize the shape and you have the answer.

Analysis

ApproachTimeSpace
Naive recursionO(2^n)O(n)
MemoizedO(n)O(n)
Bottom-up O(1)O(n)O(1)