Algorithm Day82 - Climbing Stairs
🧩 Problem Description
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
💬 Examples
Example 1
1 | Input: n = 2 |
Example 2
1 | Input: n = 3 |
💡 Intuition
This is a dynamic programming problem, equivalent to computing the Fibonacci sequence.
- Let
dp[i]be the number of ways to climbisteps. - Transition:
dp[i] = dp[i-1] + dp[i-2]. - Base cases:
dp[1] = 1,dp[2] = 2.
We can optimize space to O(1) by just keeping the last two states.
🔢 Java Code (DP Optimized)
1 | class Solution { |
⏱ Complexity Analysis
- Time: O(n) — linear iteration.
- Space: O(1) — only two variables stored.
✍️ Summary
- Equivalent to computing Fibonacci numbers.
- Use DP or iterative approach for efficiency.
- Space optimized to O(1).
Related problems
lc-746— Min Cost Climbing Stairslc-509— Fibonacci Number