刷题记录 回溯算法-5:17.电话号码的字母组合

题目:17. 电话号码的字母组合

难度:中等

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

本题非常简单

直接套模板可以很快写出

而且无需剪枝优化

算是最省心的回溯题了

代码实现(python):

两种写法

数组记录组合:

复制代码
phone_map = {
    '2': 'abc',
    '3': 'def',
    '4': 'ghi',
    '5': 'jkl',
    '6': 'mno',
    '7': 'pqrs',
    '8': 'tuv',
    '9': 'wxyz',
}
class Solution:
    def backtracking(self, digits, path, ans):
        if len(path) == len(digits):
            ans.append(''.join(path[:]))
            return

        sets = phone_map[digits[len(path)]]
        for ch in sets:
            path.append(ch)
            self.backtracking(digits, path, ans)
            path.pop()

    def letterCombinations(self, digits: str) -> List[str]:
        if len(digits) == 0:
            return []
        ans = []
        self.backtracking(digits, [], ans)
        return ans

字符串记录组合:

复制代码
phone_map = {
    '2': 'abc',
    '3': 'def',
    '4': 'ghi',
    '5': 'jkl',
    '6': 'mno',
    '7': 'pqrs',
    '8': 'tuv',
    '9': 'wxyz',
}
class Solution:
    def backtracking(self, digits, path, ans):
        if len(path) == len(digits):
            ans.append(path)
            return

        sets = phone_map[digits[len(path)]]
        for ch in sets:
            path += ch
            self.backtracking(digits, path, ans)
            path = path[:-1]

    def letterCombinations(self, digits: str) -> List[str]:
        ans = []
        if len(digits) == 0:
            return ans
        self.backtracking(digits, '', ans)
        return ans
相关推荐
databook20 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室20 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三1 天前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
聚客AI1 天前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
大怪v1 天前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django