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

相关推荐
BoBoZz192 分钟前
PolyDataContourToImageData 3D集合图像转换成等效3D二值图像
python·vtk·图形渲染·图形处理
xu_yule2 分钟前
算法基础-背包问题(01背包问题)
数据结构·c++·算法·01背包
2401_841495646 分钟前
【自然语言处理】关系性形容词的特征
人工智能·python·自然语言处理·自动识别·特征验证·关系性形容词·语言学规则和计算
蒙奇D索大6 分钟前
【数据结构】考研408 | 伪随机探测与双重散列精讲:散列的艺术与均衡之道
数据结构·笔记·学习·考研
rebekk12 分钟前
Hydra介绍
人工智能·python
我不是小upper13 分钟前
从理论到代码:随机森林 + GBDT+LightGBM 融合建模解决回归问题
人工智能·深度学习·算法·随机森林·机器学习·回归
青啊青斯17 分钟前
python markdown转word【包括字体指定】
开发语言·python·word
拾贰_C20 分钟前
【python | pytorch | warehouse】python库scipy与scikit-learn库不兼容?
pytorch·python·scipy
corpse201022 分钟前
trae下载依赖包特别慢!!!
开发语言·python
诸神缄默不语24 分钟前
Windows系统无法直接用uv安装pyqt5,但可以用uv pip安装
python