NeetCode #657LC-70Easy1-D Dynamic ProgrammingBlind 75NC 150NC 250
← Back to All Problems#657 · #70 · Climbing Stairs(爬楼梯)
📌 Problem Statement & Constraints
You are climbing a staircase with
n steps. Each move you may climb either 1 or 2 steps. Return the number of distinct ways to reach the top. Constraints: 1 <= n <= 45, so the answer fits in a 32-bit integer.💡 Core Algorithmic Approaches
- Let
dp[i]be the number of ways to reach stepi. - The last move is either a single step from
i - 1or a double step fromi - 2, sodp[i] = dp[i - 1] + dp[i - 2]. - The base cases are
dp[0] = 1(one way to stand still) anddp[1] = 1; this is the Fibonacci sequence shifted by one index. - Only the two previous values are ever needed, so two rolling variables reduce the space to O(1).
💻 Benchmark Python3 Implementation
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
prev2, prev1 = 1, 2 # ways to reach step 1 and step 2
for _ in range(3, n + 1):
prev2, prev1 = prev1, prev1 + prev2
return prev1⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): a single pass over the steps (O(1) with the rolling variables).
💾 Space Complexity
O(1): two scalars; an O(n) array also works but is unnecessary.
⚠️ Interview Pitfalls & Follow-ups
- Trying a closed-form combinatorial sum: the recurrence is the clean formulation; summing over the count of double steps invites arithmetic mistakes.
- Off-by-one in the base cases:
n = 1is 1 andn = 2is 2; an array indexed bydp[i]needs sizen + 1withdp[0] = 1. - Looping to
n - 1instead ofn: the final answer is the value at stepn, so the loop bound must be inclusive. - Confusing this with problem 746: here every stair costs exactly one move, whereas 746 attaches a different cost to each stair.