Climbing Stairs
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ n ≤ 30
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Recursive Without Memoization
BruteStanding on step i, the top can be reached either by taking a single step to i+1 or a double step to i+2 — so the number of ways to finish from step i is just the number of ways from i+1 plus the number of ways from i+2. Landing exactly on step n counts as one complete way to finish, and overshooting past n contributes nothing. Starting that recursion at step 0 and letting it branch all the way to the top answers the question, but the same step gets recomputed from scratch every time a different earlier decision happens to land back on it.
O(2^n)O(n)1class Solution {
2 private int n;
3
4 public int climbStairs(int n) {
5 this.n = n;
6 return solve(0);
7 }
8
9 private int solve(int i) {
10 if (i == n) return 1;
11 if (i > n) return 0;
12 return solve(i + 1) + solve(i + 2);
13 }
14}Optimal — Bottom-Up with O(1) Space
OptimalInstead of asking "how many ways to finish from step i", flip the question around to "how many ways to arrive at step i from the bottom" — the count for step i is just the count for step i-1 plus the count for step i-2, since the last move taken to land on i was either a single step or a double step. Only the two most recent counts are ever needed to compute the next one, so there's no need to keep a whole array — two running variables, updated as the steps are swept from the bottom to the top, are enough.
O(n)O(1)1class Solution {
2 public int climbStairs(int n) {
3 if (n <= 2) return n;
4 int prev2 = 1, prev1 = 2;
5 for (int i = 3; i <= n; i++) {
6 int cur = prev1 + prev2;
7 prev2 = prev1;
8 prev1 = cur;
9 }
10 return prev1;
11 }
12}