Climbing Stairs 解題教學:3 種解法完整比較|LeetCode 70 Best Practice

Climbing Stairs 解題教學示意圖|LeetCode 70

本文完整拆解 LeetCode 70 Climbing Stairs 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Climbing Stairs 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

 

Example 1:

Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

 

Constraints:

  • 1 <= n <= 45

Python

				
					class Solution:
    # time complexity: O(n)
    # space complexity: O(n)
    # Cashe with brute force
    # def climbStairs(self, n: int) -> int:
    #     memo = [0] * (n+1)
    #     return self.climb_Stairs(0, n, memo)

    # time complexity: O(n)
    # space complexity: O(n)
    # def climb_Stairs(self, i: int, n: int, memo: list) -> int:
    #     if (i > n):
    #         return 0
    #     if (i == n):
    #         return 1
    #     if (memo[i]):
    #         return memo[i]
    #     memo[i] = self.climb_Stairs(i+1, n, memo) + \
    #         self.climb_Stairs(i+2, n, memo)
    #     return memo[i]

    # time complexity: O(n)
    # space complexity: O(b)
    # Dynamic Programming
    # def climbStairs(self, n: int):
    #     if n == 1:
    #         return 1
    #     dp = [0] * (n + 1)
    #     dp[1] = 1
    #     dp[2] = 2
    #     for i in range(3, n+1):
    #         dp[i] = dp[i-1] + dp[i-2]
    #     return dp[n]

    # time complexity: O(n)
    # space complexity: O(1)
    # Fibonacci Number
    def climbStairs(self, n: int) -> int:
        if n == 1:
            return 1
        first = 1
        second = 2
        third = 0
        for i in range(3, n+1):
            third = first + second
            first = second
            second = third
        return second


n = 50
print(Solution().climbStairs(50))
				
			

Climbing Stairs 解題思路

爬到第 n 階的方法數,等於「從第 n-1 階再爬一步」加上「從第 n-2 階再爬兩步」的方法數——這就是費氏數列。既然每個狀態只依賴前兩個,就不需要整個陣列,兩個變數滾動著走就行。

Climbing Stairs 演算法步驟

  1. 若 n 小於等於 2 直接回傳 n。
  2. 初始化 prev = 1(到第 1 階)、cur = 2(到第 2 階)。
  3. 從第 3 階開始迭代到第 n 階。
  4. 每一步令 next = prev + cur,然後 prev = cur、cur = next,最後回傳 cur。

Climbing Stairs 複雜度分析

項目複雜度
時間複雜度O(n)
空間複雜度O(1)

單一迴圈跑 n-2 次,每次常數時間,時間為 O(n)。只保留兩個變數,空間 O(1)。若用矩陣快速冪可進一步降到 O(log n),但本題資料量不需要。

Climbing Stairs 的邊界情況與常見錯誤

  • n 等於 1 或 2 要特判,否則迴圈初始值會出錯。
  • 純遞迴不加記憶化會是 O(2^n),n 稍大就爆。
  • n 很大時結果會超出 32 位元整數範圍。
  • 題目若改成「一次可爬 1 到 k 階」,就要改成前 k 項求和。

Climbing Stairs 其他解法比較

解法時間空間說明
純遞迴O(2^n)O(n)最直覺但重複計算嚴重
記憶化遞迴或 DP 陣列O(n)O(n)正確且好懂,空間可再優化
雙變數滾動O(n)O(1)本文採用