代码改变世界

[LeetCode] 17. Letter Combinations of a Phone Number_Medium tag: backtracking

2019-07-10 09:41  Johnson_强生仔仔  阅读(235)  评论(0编辑  收藏  举报

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.

这个题目利用backtracking + DFS, 注意不能直接按照permutation来,会添加不需要的结果,所以我们用一个pos来控制每次要按照顺序来,类似于只要按顺序的permutations。

用一个dictionary来存数字与字母之间的mapping, 然后pos来告知现在在digits中的位数。

note:

edge case:

"" => []

 

Code:

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits: return []
        self.map = {'2': "abc", '3': "def", '4':"ghi", '5': "jkl", '6': "mno", '7':"pqrs", '8': "tuv", '9': "wxyz"}
        ans = []
        self.helper(digits, ans, "", 0)
        return ans
    
    def helper(self, digits: str, ans: List[str], temp: str, pos: int) -> None:
        if pos == len(digits):
            ans.append(temp)
        elif pos < len(digits):
            for c in self.map[digits[pos]]:
                self.helper(digits, ans, temp + c, pos + 1)