代码随想录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天完结🎉今日有点简单。

相关推荐
小白学大数据3 分钟前
构建1688店铺商品数据集:Python爬虫数据采集与格式化实践
开发语言·爬虫·python
闲人编程6 分钟前
用Python和Telegram API构建一个消息机器人
网络·python·机器人·api·毕设·telegram·codecapsule
却道天凉_好个秋14 分钟前
目标检测算法与原理(二):Tensorflow实现迁移学习
算法·目标检测·tensorflow
大邳草民18 分钟前
深入理解 Python 的“左闭右开”设计哲学
开发语言·笔记·python
暴风鱼划水39 分钟前
三维重建【4-A】3D Gaussian Splatting:代码解读
python·深度学习·3d·3dgs
Geoking.1 小时前
PyTorch 中 model.eval() 的使用与作用详解
人工智能·pytorch·python
nn在炼金1 小时前
图模式分析:PyTorch Compile组件解析
人工智能·pytorch·python
执笔论英雄1 小时前
【大模型训练】zero2 梯度分片
pytorch·python·深度学习
Danceful_YJ1 小时前
25.样式迁移
人工智能·python·深度学习