This is LeetCode #70: Climbing Stairs — the perfect first DP problem! It's literally Fibonacci in disguise. 🪜
💡 Think of it like this: You're climbing a staircase with n steps. Each time you can take 1 step or 2 steps. How many different ways can you reach the top?
The DP Insight: To reach step n, you came from either step n-1 (took 1 step) or step n-2 (took 2 steps). So:
ways(n) = ways(n-1) + ways(n-2) — That's Fibonacci!
💭 Your turn! Take what you learned above and write the code yourself. Struggling is part of learning! 🧠
This is the simplest form of DP. Master this pattern and you'll handle House Robber, Coin Change, and many more DP problems!
def climbStairs(n):
if n <= 2:
return n
a, b = 1, 2 # dp[1]=1, dp[2]=2
for i in range(3, n + 1):
a, b = b, a + b # dp[i] = dp[i-1] + dp[i-2]
return b
# Only 2 variables needed! O(n) time, O(1) space
climbStairs(5)
8