標籤:ber like 個數 自動 def map ike ica else
題目:
Given a string containing digits from 2-9
inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: "23"Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
這道題翻譯成中文其實比較簡單,就是給你數字,讓你輸出數字映射的字母所有可能出現的組合情況。同一個數字映射的字母不會組合到一起,不區分字母順序,每個字母組合必須包含所有數字映射的一個字母。
這裡利用遞迴可以輕鬆解決,剛好最近看了一些產生器相關的資料,索性利用遞迴產生器,更加簡潔方便一些。
代碼如下:
1 class Solution: 2 def letterCombinations(self, digits): 3 return list(self.recur(digits))
4 def recur(self, x): #由於LeetCode驗證代碼時不會自動將產生器轉化為列表,所以只能產生器寫在外面,主函數只列印答案 5 dic = {‘2‘: ‘abc‘, ‘3‘: ‘def‘, ‘4‘: ‘ghi‘, ‘5‘: ‘jkl‘, ‘6‘: ‘mno‘, ‘7‘: ‘pqrs‘, ‘8‘: ‘tuv‘, ‘9‘: ‘wxyz‘} 6 if len(x) == 0: #將digits為空白值拿出來特別處理 7 return [] 8 for i in dic[x[0]]: 9 if len(x) == 1: #遞迴到digits只剩最後一個值挨個產生該值的映射 10 yield i11 else:12 for j in self.letterCombinations(x[1:]): #這裡返回的產生器,可以用來迭代13 yield i + j #拼接字串,一層一層向上返還
LeetCode演算法題python解法:17. Letter Combinations of a Phone Number