刷题笔记回溯数据结构Leetcode 78子集赵海波2024-08-282024-08-30 17. 电话号码的字母组合 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 示例 1: 12>输入:digits = "23">输出:["ad","ae","af","bd","be","bf","cd","ce","cf"] 示例 2: 12>输入:digits = "">输出:[] 示例 3: 12>输入:digits = "2">输出:["a","b","c"] 代码: 1234567891011121314151617181920212223242526class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ MAPPING = "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" n = len(digits) if n == 0: return [] ans = [] path = [''] * n def dfs(i): # 当遍历到最后一位的时候退出 if i == n: ans.append(''.join(path)) print(ans) return # 从字典找取出下一位的字符,然后逐个遍历进入 for c in MAPPING[int(digits[i])]: path[i] = c dfs(i + 1) dfs(0) return ans