17. 电话号码的字母组合




可参考:https://www.cnblogs.com/panweiwei/p/14025143.html

class Solution(object):
    def __init__(self):
        self.res = []
        self.mydict = {1: "", 2: "abc", 3: "def",
                       4: "ghi", 5: "jkl", 6: "mno",
                       7: "pqrs", 8: "tuv", 9: "wxyz"}

    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        # 特判
        if not digits:
            return []
        # 将数字串转成list[int]类型
        nums = []
        for ch in digits:
            nums.append(int(ch))
        self.dfs(nums, 0, [])
        return self.res

    def dfs(self, nums, cur, temp):
        # 定义递归出口:若临时串长度达到要求,则找到一个新答案
        if cur == len(nums):
            self.res.append("".join(temp))
            return
        digits = self.mydict[nums[cur]]
        for digit in digits:
            # 用临时串记录当前数字
            temp.append(digit)
            # 递归
            self.dfs(nums, cur + 1, temp)
            # 回退
            temp.pop()
posted @ 2020-11-23 16:25  人间烟火地三鲜  阅读(302)  评论(0编辑  收藏  举报