LeetCode17. 电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
LeetCode17. 电话号码的字母组合_第1张图片
示例:
输入:“23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

来源:力扣(LeetCode)
链接: https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number

1、暴力遍历O(n^2)

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        dic = {"2":"abc","3":"def","4":"ghi","5":"jkl",
        "6":"mno","7":"pqrs","8":"tuv","9":"wxyz"}
        if digits == '':return []
        # 这里不能为[],否则后面res不能赋值总为空
        res = [""]
        for char in digits:
            # 列表表达式
            res =[res2 + res1 for res2 in res for res1 in dic[char]]
        return res

2、递归

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        dic = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
               "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}
        if not digits: return []
        n = len(digits)
        # 这里采用了append所以可以为[]
        res = []

        # i记录当前字符长度,char记录当前i长的字符串
        def search(i, char):
            # 当前该种情形已到达n长,加到res中
            if i == n:
                res.append(char)
                return
            for alp in dic[digits[i]]:
                search(i + 1, char + alp)

        search(0, "")
        return res

你可能感兴趣的:(leetcode,leetcode)