LeetCode in Python 17. Letter Combinations of a Phone Number

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.

 

也是一个典型DFS解法,用path记录当前路径,长度达到要求时加入res,在for循环中递归调用函数。 

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        
        numDict = {
            '2': ['a', 'b', 'c'],
            '3': ['d', 'e', 'f'],
            '4': ['g', 'h', 'i'],
            '5': ['j', 'k', 'l'],
            '6': ['m', 'n', 'o'],
            '7': ['p', 'q', 'r', 's'],
            '8': ['t', 'u', 'v'],
            '9': ['w', 'x', 'y', 'z']
        }
        
        res = []
        if len(digits) == 0:
            return res
        
        def dfs(path, level):
            if level == len(digits):
                res.append(path)
                return
            for c in numDict[digits[level]]:
                dfs(path+c, level+1)
                
        dfs('', 0)
        return res

  

posted @ 2019-07-11 20:14  bossman  阅读(126)  评论(0编辑  收藏  举报