Climbing Stairs
You are climbing a staircase with n steps to reach the top Each time you can climb either 1 or 2 steps Return the number of distinct ways to climb to the top Example: n = 2 => 2 (1+1 or 2) Example: n = 3 => 3 (1+1+1, 1+2, 2+1)
Count the ways to reach the top when you can take 1 or 2 steps at a time. It looks like a brute-force recursion problem, but it's actually your first real dynamic programming question. Once you see the Fibonacci pattern hiding inside, a whole category of DP problems clicks into place.
Examples
You write
climb_stairs(n: int)
Example 1
- Input
- n = 2
- returns
- 2
Example 2
- Input
- n = 3
- returns
- 3
The pattern behind it
Dynamic Programming
I reach for it when
- Brute force repeats the same subproblem.
- You are asked for a count, a minimum or a maximum.
Say this before you type. Say the state in one sentence, then say which smaller states it reads from.
All 37 Dynamic Programming problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Each locked part opens in the editor once the part before it passes.