快轉到主要內容
  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 - 1i - 2 來,所以把兩個 predecessor 的方法數相加,最後用兩個變數壓縮空間。

相關文章

LeetCode 1971: Find if Path Exists in Graph
·2 分鐘
LeetCode Easy Graph Union-Find
LeetCode 1971 解題筆記,依照原始 learning note 重新整理
LeetCode 496: Next Greater Element I
·1 分鐘
LeetCode Daily Easy Array Stack Monotonic-Stack Hash-Map Next-Greater-Element
單調遞減堆疊處理 nums2,預先建立下一個更大元素對照表,回答 nums1 查詢。
LeetCode 20: Valid Parentheses
·1 分鐘
LeetCode Daily Easy String Stack Data-Structures Parentheses Validation
使用堆疊解決有效括號問題
LeetCode 84: Largest Rectangle in Histogram
·1 分鐘
LeetCode Daily Hard Array Stack Monotonic-Stack Dynamic-Programming Geometry Histogram
使用單調堆疊解決直方圖中最大矩形面積問題
LeetCode 1071: Greatest Common Divisor of Strings
·1 分鐘
LeetCode Daily Easy String Gcd Math
LeetCode 解題紀錄
LeetCode 643: Maximum Average Subarray I
·1 分鐘
LeetCode Daily Easy Sliding-Window
LeetCode 解題紀錄