编程语言
首页 > 编程语言> > leetcode练习——回溯算法(电话号码的字母组合)

leetcode练习——回溯算法(电话号码的字母组合)

作者:互联网

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
在这里插入图片描述

官方解法:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/solution/dian-hua-hao-ma-de-zi-mu-zu-he-by-leetcode-solutio/

解法一:哈希表+回溯

(20ms/15.1MB)

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return list()
        
        phoneMap = {
            "2": "abc",
            "3": "def",
            "4": "ghi",
            "5": "jkl",
            "6": "mno",
            "7": "pqrs",
            "8": "tuv",
            "9": "wxyz",
        }

        def backtrack(index: int):
            if index == len(digits):
                combinations.append("".join(combination))
            else:
                digit = digits[index]
                for letter in phoneMap[digit]:
                    combination.append(letter)
                    backtrack(index + 1)
                    combination.pop()

        combination = list()
        combinations = list()
        backtrack(0)
        return combinations

(28ms/15.1MB)

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return list()
        
        phoneMap = {
            "2": "abc",
            "3": "def",
            "4": "ghi",
            "5": "jkl",
            "6": "mno",
            "7": "pqrs",
            "8": "tuv",
            "9": "wxyz",
        }

        groups = (phoneMap[digit] for digit in digits)
        return ["".join(combination) for combination in itertools.product(*groups)]
        # itertools.product(*iterables[, repeat]) # 对应有序的重复抽样过程,以元组的形式,根据输入的可遍历对象生成笛卡尔积,与嵌套的for循环类似。

repeat是一个关键字参数,指定重复生成序列的次数。


力扣 (LeetCode)链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-medium/xv8ka1/

标签:digits,digit,return,combination,combinations,回溯,字母组合,leetcode,def
来源: https://blog.csdn.net/strivequeen/article/details/120564679