题目描述:
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"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