LeetCode 题解工作台
爬楼梯
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? 示例 1: 输入: n = 2 输出: 2 解释: 有两种方法可以爬到楼顶。 1. 1 阶 + 1 阶 2. 2 阶 示例 2: 输入: n = 3 输出: 3 解释: 有三种方法…
3
题型
8
代码语言
3
相关题
当前训练重点
简单 · 状态·转移·动态规划
答案摘要
我们定义 表示爬到第 阶楼梯的方法数,那么 可以由 $f[i - 1]$ 和 $f[i - 2]$ 转移而来,即: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
示例 1:
输入:n = 2 输出:2 解释:有两种方法可以爬到楼顶。 1. 1 阶 + 1 阶 2. 2 阶
示例 2:
输入:n = 3 输出:3 解释:有三种方法可以爬到楼顶。 1. 1 阶 + 1 阶 + 1 阶 2. 1 阶 + 2 阶 3. 2 阶 + 1 阶
提示:
1 <= n <= 45
解题思路
方法一:递推
我们定义 表示爬到第 阶楼梯的方法数,那么 可以由 和 转移而来,即:
初始条件为 ,,即爬到第 0 阶楼梯的方法数为 1,爬到第 1 阶楼梯的方法数也为 1。
答案即为 。
由于 只与 和 有关,因此我们可以只用两个变量 和 来维护当前的方法数,空间复杂度降低为 。
时间复杂度 ,空间复杂度 。
class Solution:
def climbStairs(self, n: int) -> int:
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return b
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) for iterative or memoized DP, since each step is computed once. Space complexity is O(n) for the DP array or memoization table, reducible to O(1) with two-variable optimization. The recurrence ensures linear growth without recomputation. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Asks for the number of ways to reach step n using allowed steps.
- question_mark
Hints at using previous step results, indicating dynamic programming pattern recognition.
- question_mark
Tests understanding of optimizing space from DP array to constant variables.
常见陷阱
外企场景- error
Attempting plain recursion without memoization leads to exponential time complexity.
- error
Confusing step sequences, double-counting combinations instead of counting distinct paths.
- error
Ignoring base cases or incorrectly initializing dp array, causing off-by-one errors.
进阶变体
外企场景- arrow_right_alt
Changing allowed steps to 1, 2, or 3 alters the state transition and requires adjusting the DP recurrence.
- arrow_right_alt
Finding minimum steps to reach the top instead of counting distinct ways changes the problem to a min-path DP variant.
- arrow_right_alt
Adding constraints like broken steps introduces conditional checks in the transition formula.