代码随想录27期|Python|Day25|回溯算法|216.组合总和III|17.电话号码的字母组合

216. 组合总和 III

本题和之前一题的区别就是字符个数放开,但是可用数字变成了[1, 9]。思路和之前的某个找二叉树最大值比较像,复用前一天的题目的代码,假如一个count = n的全局变量即可。

python 复制代码
class Solution(object):
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        res = []
        count = n
        self.backtracking(k, 1, [], res, count)
        return res

    def backtracking(self, k, start_idx, path, res, count):
        # 终止条件
        if len(path) == k:
            if count == 0:
                res.append(path[:])  # 加入res
            return  # 回溯
        for i in range(start_idx, 10):
            path.append(i)
            count -= i
            self.backtracking(k, i + 1, path, res, count)  # 起始位置变成i+1
            count += i
            path.pop()  # 回溯

这里在backtracking中的递归还可以写成隐藏形式的:

python 复制代码
            self.backtracking(k, i + 1, path, res, count - i)  # 起始位置变成i+1

17. 电话号码的字母组合

首先看到这个小灵通界面很容易想到字典 (虽然这里是利用了list的天然数字索引)。然后定义一个指针指向当前digits中取出的数字。其余都是上一题的改编。

1、参数和返回值:由于是全部遍历,修改的是全局变量,所以可以没有返回值;参数就是需要更新的指针idx和digits,其余的path和res可以改成self;

2、终止条件:idx指向digits的末尾,添加全部的path进入res;

3、中间处理:首先需要取出digits中idx对应的数字,找到map映射的字符串,剩下的就和模版题一样了。

python 复制代码
class Solution(object):
    def __init__(self):
        self.digi_map = [
            "",  # 0
            "",  # 1
            "abc",  # 2
            "def",  # 3
            "ghi",  # 4
            "jkl",  # 5
            "mno",  # 6
            "pqrs",  # 7
            "tuv",  # 8
            "wxyz"  # 9
        ]

    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if not len(digits):
            return []
        path = ""
        res = []
        self.backtracking(0, path, res, digits)
        return res
    
    def backtracking(self, idx, path, res, digits):
        # 终止条件
        if idx == len(digits):  # 当前的idx指向digits末尾
            res.append(path[:])  # 加入res
            return  # 回溯
        # 从字符串中取出int类型的数字
        digit = int(digits[idx])
        # 找到对应的字符串
        letters = self.digi_map[digit]
        # 遍历
        for i in range(len(letters)):
            path += letters[i]
            self.backtracking(idx + 1, path, res, digits)  # 起始位置变成idx + 1
            path = path[:-1]  # 回溯

OMG第25天完结🎉今日有点简单。

相关推荐
phoenix@Capricornus1 小时前
反向传播算法——矩阵形式递推公式——ReLU传递函数
算法·机器学习·矩阵
Inverse1621 小时前
C语言_动态内存管理
c语言·数据结构·算法
数据与人工智能律师1 小时前
虚拟主播肖像权保护,数字时代的法律博弈
大数据·网络·人工智能·算法·区块链
成功人chen某2 小时前
配置VScodePython环境Python was not found;
开发语言·python
wuqingshun3141592 小时前
蓝桥杯 16. 外卖店优先级
c++·算法·职场和发展·蓝桥杯·深度优先
2301_786964362 小时前
EXCEL Python 实现绘制柱状线型组合图和树状图(包含数据透视表)
python·microsoft·excel
skd89992 小时前
小蜗牛拨号助手用户使用手册
python
「QT(C++)开发工程师」2 小时前
STM32 | FreeRTOS 递归信号量
python·stm32·嵌入式硬件
YouQian7723 小时前
2025春训第十九场
算法
CodeJourney.3 小时前
基于MATLAB的生物量数据拟合模型研究
人工智能·爬虫·算法·matlab·信息可视化