题目

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
17、电话号码的字母组合 - 图1
示例:

  1. 输入:"23"
  2. 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。

答案

#
# @lc app=leetcode.cn id=17 lang=python3
#
# [17] 电话号码的字母组合
#

# @lc code=start
from typing import List


class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return []
        KEY = {
            '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 = []

        def helper(index, item_ans):
            if len(digits) == len(item_ans):
                res.append(item_ans[:])
                return

            for i in KEY[digits[index]]: 
                dic = KEY[digits[index]]
                item_ans += i
                helper(index + 1, item_ans)
                item_ans = item_ans[:-1]

        helper(index=0, item_ans='')

        return res


Solution().letterCombinations('23')
# @lc code=end

Note

dfs+回溯
非常巧妙地一个变量 index
第一次执行helper函数 index 是 0 ,匹配的是第一个输入数字的字母
第二次递归走到helper函数 index 变 1 ,匹配到第二个数字对应的字母
然后走循环,循环的都是第二个数字匹配到的字母,循环完成函数退出返回第一个函数 index 还是 0