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

LeetCode 17: Letter Combinations of a Phone Number

·1 分鐘· ·
LeetCode Medium Hash-Table String Backtracking
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2022-10-20

  • 提交紀錄:Runtime Error ×8 → Accepted → Runtime Error → Accepted ×2

解題思路
#

第 i 層處理 digits[i],枚舉它對應的每個字母接到目前的字串後面,處理完所有數字就記錄(Backtracking 模板)。digits 是空的時要回傳 [],不是 [""]。

我的嘗試
#

這題提交了 12 次,幾乎都是 Python 的作用域問題:

  • 把遞迴寫成另一個 method,在裡面直接用 digits 和 dic,但它們是 letterCombinations 的區域變數,另一個 method 看不到(NameError),中間還夾著幾次語法錯誤。
  • 2022-11 重寫時把字典存成 self.d2l、把 digits 當參數往下傳,才 AC。

正確解法
#

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return []
        letters = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
                   "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}
        res = []
        def dfs(i, path):
            if i == len(digits):
                res.append(path)
                return
            for c in letters[digits[i]]:
                dfs(i + 1, path + c)
        dfs(0, "")
        return res

複雜度
#

時間 O(4^n · n),空間 O(n)。

要特別避免的錯誤
#

  • 另一個 method 讀不到這個 method 的區域變數(digits、dic),要當參數傳或用內部函式。
  • 空字串回傳 []。

面試口說整理
#

我用回溯,每一層處理一個數字,把它對應的每個字母接上去,處理完所有數字就記錄;輸入是空字串時直接回傳空的 list。時間 O(4^n · n)。

相關文章

LeetCode 5: Longest Palindromic Substring
·1 分鐘
LeetCode Medium Two-Pointers String Dynamic-Programming Manacher
LeetCode 5 解題筆記:中心擴展,每個位置當奇數和偶數長度的中心往外擴;區間 DP 的話 i 要從大到小
LeetCode 1189: Maximum Number of Balloons
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 1189 解題筆記:每個字母可以組幾個 balloon 是 次數 // 需要數,l 和 o 需要兩個,取最小值
LeetCode 1002: Find Common Characters
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 1002 解題筆記:每個單字各自計數,對所有 Counter 取交集(每個字元取最小次數),再展開
LeetCode 929: Unique Email Addresses
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 929 解題筆記:用 @ 切開,只處理 local 的部分(+ 之後丟掉、去掉 .),接回 domain 後放進集合
LeetCode 953: Verifying an Alien Dictionary
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 953 解題筆記:把字母對應到外星順序的 index,相鄰兩個單字找第一個不同的字元比較,沒有不同時短的要在前面
LeetCode 884: Uncommon Words from Two Sentences
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 884 解題筆記:把兩個句子合起來數每個單字的次數,只出現一次的就是答案