↓快轉到主要內容
  1. LeetCode/

LeetCode 70: Climbing Stairs

·2 分鐘· ·
LeetCode Easy Dynamic-Programming
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2026-04-20 來源:Day 9 learning note

學習脈絡
#

這篇是從 learning note 裡該 LeetCode 題目的段落重新整理出來的版本。我保留當天筆記中的修正點、比較點、容易犯錯的地方,並移除同一天其他非 LeetCode 主題,避免文章內容混題。

當天筆記摘錄
#

LC 70 - Climbing Stairs
#

  • Status: Completed.
  • Pattern: Fibonacci-style 1D DP.

State
#

dp[i] = number of distinct ways to reach step i

Base Case
#

dp[0] = 1
dp[1] = 1

dp[0] = 1 means there is one way to start before taking any steps: do nothing.

Transition
#

dp[i] = dp[i - 1] + dp[i - 2]

To reach step i, the last move must come from step i - 1 with one step or from step i - 2 with two steps.

Complexity
#

Time: O(n)
Space: O(n) with array, O(1) with two variables

整理補充
#

這題不要只說「就是 Fibonacci」。比較穩的說法是:dp[i] 是到第 i 階的 ordered step sequences 數量。最後一步只可能從 i - 1 走 1 階,或從 i - 2 走 2 階,所以兩個來源互斥,可以相加。提交版用 n <= 2 處理小 case,後面用兩個變數滾動同一個 recurrence。

正確解法
#

上面的筆記保留了推理脈絡和當天需要修正的點。下面是我會提交的版本。

class Solution:
    def climbStairs(self, n: int) -> int:
        if n <= 2:
            return n
        prev2, prev1 = 1, 2
        for _ in range(3, n + 1):
            prev2, prev1 = prev1, prev1 + prev2
        return prev1

複雜度
#

Time O(n), Space O(1).

要特別避免的錯誤
#

  • Off-by-one base cases.
  • Thinking order does not matter; sequences of 1/2 steps are distinct.

面試口說整理
#

我會把這題講成 ordered step sequences 的 counting DP。dp[i] 是站在第 i 階的方法數;最後一步只能從 i - 1 或 i - 2 來,所以把兩個 predecessor 的方法數相加,最後用兩個變數壓縮空間。

相關文章

LeetCode 338: Counting Bits
·1 分鐘
LeetCode Easy Dynamic-Programming Bit-Manipulation
LeetCode 338 解題筆記:dp[i] = dp[i » 1] + (i & 1),或 dp[i] = dp[i - 最高位的 2 的次方] + 1
LeetCode 1137: N-th Tribonacci Number
·1 分鐘
LeetCode Easy Math Dynamic-Programming Memoization
LeetCode 1137 解題筆記:跟 Fibonacci 一樣,用三個變數滾動;小心 T0 = 0、T1 = T2 = 1 的起始值和迴圈範圍
LeetCode 1025: Divisor Game
·1 分鐘
LeetCode Easy Math Dynamic-Programming Brainteaser Game-Theory
LeetCode 1025 解題筆記:dp[i] = 存在 i 的因數 x 讓 dp[i - x] 是輸;觀察後答案就是 n 是偶數
LeetCode 509: Fibonacci Number
·1 分鐘
LeetCode Easy Math Dynamic-Programming Recursion Memoization
LeetCode 509 解題筆記:一維 DP 的起點:只需要前兩項,用兩個變數滾動
LeetCode 392: Is Subsequence
·1 分鐘
LeetCode Easy Two-Pointers String Dynamic-Programming
LeetCode 392 解題筆記:兩個指針,t 的指針一直往前,對上 s 的字元時 s 的指針也前進;兩邊的邊界都要檢查
LeetCode 119: Pascal's Triangle II
·1 分鐘
LeetCode Easy Array Dynamic-Programming
LeetCode 119 解題筆記:只要第 rowIndex 列,用一維陣列從右往左更新,空間 O(k)