solulubeta
Sign in
Recursion & Memo / From recursion to memoization
03.03 · Problem

Climbing Stairs

Easy 1-D DP: count ways LC 70 Free

You climb a staircase of n steps, 1 or 2 steps at a time. In how many different ways can you reach the top?

Examples

Example 1

Input:  n = 2
Output: 2

1 + 1, or 2.

Example 2

Input:  n = 3
Output: 3

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

Example 3

Input:  n = 1
Output: 1

Constraints

1 ≤ n ≤ 45 (the answer fits in an int)

Derive it

Hint

Your first move is 1 step or 2 steps. How many ways are there to finish after each one?

Still stuck? Derive it step by step. Each answer adds a line to the code:

Solution steps
  1. Promise: ways(n) = number of ways to climb exactly n steps.
  2. Base cases: n == 0 → 1 (you’re at the top). n < 0 → 0.
  3. Recurrence: ways(n − 1) + ways(n − 2).
  4. Memo: int[n + 1] filled with -1. Time O(n).

Table: dp[0] = dp[1] = 1, then dp[i] = dp[i − 1] + dp[i − 2] going up.

Change one rule: steps of 1, 2 or 3? Add ways(n − 3).

Loading the workspace…
Mark this problem as solved when you are finished.

Item 22 of 44 · updated 2026-10-13