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

相关推荐
吃好睡好便好2 小时前
提取矩阵某一行或某一列元素
开发语言·人工智能·线性代数·算法·matlab·矩阵
小江的记录本5 小时前
【JVM虚拟机】垃圾回收GC:四种引用类型:强引用、软引用、弱引用、虚引用(附《思维导图》+《面试高频考点清单》)
java·jvm·spring boot·后端·python·spring·面试
APIshop5 小时前
Python 获取 1688 商品采集 API 接口 | 工厂货源自动化对接商品信息 | 无需选品
运维·python·自动化
deepin_sir5 小时前
10 - 函数
开发语言·python
云泽8086 小时前
笔试算法 -位运算篇(二):从唯一字符到消失数字
c++·算法·位运算
charlee446 小时前
《GIS基础原理与技术实践》配套案例(Python版)
python·conda·numpy·gis·环境配置
枫叶林FYL6 小时前
项目十:事件溯源仓储管理系统(WMS)仿真实现
开发语言·python
ʚ希希ɞ ྀ6 小时前
不同路径|| -- dp
算法
IT 行者7 小时前
SimHash 与 MinHash:相似性计算的双子星算法
算法·hash·比对