本文完整拆解 LeetCode 91 Decode Ways 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Decode Ways 一次弄懂。
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
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1" 'B' -> "2" ... 'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF"with the grouping(1 1 10 6)"KJF"with the grouping(11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: s = "12" Output: 2 Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: s = "226" Output: 3 Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
Example 3:
Input: s = "06"
Output: 0
Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").
Constraints:
1 <= s.length <= 100scontains only digits and may contain leading zero(s).
Python
# time complexity: O(n)
# space complexity: O(n)
from functools import lru_cache
class Solution:
@lru_cache(None)
def recursiveWithMemo(self, index: int, s: str) -> int:
if index == len(s):
return 1
if s[index] == '0':
return 0
if index == len(s) - 1:
return 1
answer = self.recursiveWithMemo(index + 1, s)
if int(s[index: index + 2]) <= 26:
answer += self.recursiveWithMemo(index + 2, s)
return answer
def numDecodings(self, s: str) -> int:
return self.recursiveWithMemo(0, s)
s = "12"
print(Solution().numDecodings(s))
LeetCode 題目延伸練習
同系列的其他解題筆記,建議一起練:
Decode Ways 解題思路
解碼方法數是典型的線性 DP:走到第 i 個字元時,方法數等於「把它單獨當一個字母」加上「和前一個字元合併成兩位數字母」的方法數。難點全在邊界——0 不能單獨成字,兩位數必須落在 10 到 26 之間。
Decode Ways 演算法步驟
- 若字串為空或開頭是 0,直接回傳 0。
- 初始化 prev2 = 1、prev1 = 1(分別代表空字串與第一個字元的方法數)。
- 從索引 1 走訪字串:若 s[i] 不是 0,cur 先加上 prev1。
- 若 s[i-1..i] 組成的兩位數介於 10 到 26,cur 再加上 prev2;接著滾動更新 prev2、prev1。
Decode Ways 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(n) |
| 空間複雜度 | O(1) |
單次線性掃描,每步做常數次判斷與加法,時間 O(n)。只保留前兩個狀態,空間壓到 O(1)。這題的價值在邊界判斷而不在複雜度。
Decode Ways 的邊界情況與常見錯誤
- 開頭為 0 直接無解,必須先擋掉。
- 字串中間出現 “0” 時只能靠前一位組成 10 或 20,否則整體無解。
- “06” 不是合法的兩位數,判斷時要確認十位數不是 0。
- 答案可能很大,注意整數範圍。
Decode Ways 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 純遞迴列舉所有切法 | O(2^n) | O(n) | 重複計算嚴重 |
| 記憶化遞迴或 DP 陣列 | O(n) | O(n) | 好懂,空間可再優化 |
| 雙變數滾動 DP | O(n) | O(1) | 本文採用 |
