Introduction
The Climbing Stairs problem is one of the most popular Dynamic Programming interview questions.
You are given:
n stairs At every step, you can climb:
1 stair or 2 stairsGoal:
Find total number of distinct ways to reach the top.Example:
n = 4Output = 5Ways:
1+1+1+11+1+2
1+2+1 2+1+1 2+2
This problem is a direct application of:
Fibonacci DP Constraints
1 <= n <= 45 Observation
To reach stair:
n You can come from:
n - 1 or n - 2Therefore:
dp[n] = dp[n-1] + dp[n-2]This is exactly the Fibonacci recurrence.
Approach 1 : Memoization
Explanation
Use recursion and store previously computed answers.
Steps:
- Solve recursively.
- Save result.
- Reuse stored values.
- Avoid repeated calculations.
Dry Run
n = 4ways(4) = ways(3) + ways(2) = 3 + 2 = 5Memo Table:
dp[1] = 1
dp[2] = 2
dp[3] = 3dp[4] = 5
Approach 2 : Tabulation
Explanation
Build answers from smaller values.
Base Cases:
dp[1] = 1dp[2] = 2
Transition:
dp[i] = dp[i-1] + dp[i-2]Approach 3 : Space Optimized DP
Explanation
Only previous two answers are required.
Instead of storing an entire DP array:
prev2prev1Use two variables.
This reduces:
Space Complexity to O(1)Practice