題目描述:git
給定一個僅包含數字 2-9
的字符串,返回全部它能表示的字母組合。app
給出數字到字母的映射以下(與電話按鍵相同)。注意 1 不對應任何字母。spa
示例:code
輸入:"23" 輸出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if len(digits) == 0: return [] d = {1: "", 2: "abc", 3: "def", 4: "ghi", 5: "jkl", 6: "mno", 7: "pqrs", 8: "tuv", 9: "wxyz"} def dfs(digits, index, path, res, d): if index == len(digits): res.append("".join(path)) return digit = int(digits[index]) for c in d.get(digit, []): path.append(c) dfs(digits, index + 1, path, res, d) path.pop() res = [] dfs(digits, 0, [], res, d) return res
class Solution: def letterCombinations(self, digits: str): keys = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'} words= [keys[_] for _ in digits if _ in keys] if len(words) == 0: return [] else: ans = [_ for _ in words[0]] for i in range(1,len(words)): temp = ans for j in range(len(words[i])): a = [(_ + words[i][j]) for _ in temp] if j == 0: ans = a else: ans += a return ans