leetcode hot100 17. 电话号码的字母组合 medium 递归回溯

每一层选择"当前数字"对应的一个字母。

python 复制代码
phone = {
    "2": "abc",
    "3": "def",
    "4": "ghi",
    "5": "jkl",
    "6": "mno",
    "7": "pqrs",
    "8": "tuv",
    "9": "wxyz"
}

切片回溯

python 复制代码
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return []

        phone = {
            "2": "abc", "3": "def",
            "4": "ghi", "5": "jkl",
            "6": "mno", "7": "pqrs",
            "8": "tuv", "9": "wxyz"
        }

        res = []

        def backtrack(digits, tmp):  #(待选列表,已有排列)
        	 #待选列表为空(所有数字有选完了)
            if not digits:
                res.append(tmp)  # 当前排列加入res
                return 

            letters = phone[digits[0]]   # 待选列表的第一个数字,对应的phone字母
            for ch in letters:
                # 递归,继续选下一个digits数字
                backtrack(digits[1:], tmp + ch)

    
        backtrack(digits, "")
        return res

时间复杂度:O(3ⁿ × n)

每个数字平均对应 3 个字母,字符串长度 n

空间复杂度:

切片写法每层都会创建新字符串:O(n^2)

相关推荐
wj3055853782 小时前
课程 9:模型测试记录与 Prompt 策略
linux·人工智能·python·comfyui
星寂樱易李2 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python
qingfeng154152 小时前
企业微信机器人开发:如何实现自动化与智能运营?
人工智能·python·机器人·自动化·企业微信
彦为君5 小时前
Agent 安全:从权限提示到沙箱隔离
python·ai·ai编程
PILIPALAPENG6 小时前
Python 语法速成指南:前端开发者视角(JS 类比版)
前端·人工智能·python
用户8356290780517 小时前
Python 操作 PowerPoint 页眉与页脚指南
后端·python
枫叶林FYL7 小时前
项目九:异步高性能爬虫与数据采集中枢 —— 基于 Crawl<sub>4</sub>AI 与 Playwright 的现代化数据采集平台 项目总览
爬虫·python·深度学习·wpf
猫猫的小茶馆8 小时前
【Python】函数与模块化编程
linux·开发语言·arm开发·驱动开发·python·stm32
Miss_min8 小时前
128K长序列数据生成
开发语言·python·深度学习