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

相关推荐
Crossoads5 分钟前
【数据结构】排序算法---桶排序
c语言·开发语言·数据结构·算法·排序算法
扎克begod10 分钟前
JAVA并发编程系列(9)CyclicBarrier循环屏障原理分析
java·开发语言·python
自身就是太阳13 分钟前
2024蓝桥杯省B好题分析
算法·职场和发展·蓝桥杯
Book_熬夜!30 分钟前
Python基础(九)——正则表达式
python·正则表达式·php
LQS202036 分钟前
基于Python实现一个浪漫烟花秀
开发语言·python
孙小二写代码37 分钟前
[leetcode刷题]面试经典150题之1合并两个有序数组(简单)
算法·leetcode·面试
QXH20000037 分钟前
数据结构—单链表
c语言·开发语言·数据结构
梅如你37 分钟前
python批量对遥感影像进行归一化与数据清洗
开发语言·python
imaima66638 分钟前
数据结构----栈和队列
开发语言·数据结构
little redcap42 分钟前
第十九次CCF计算机软件能力认证-1246(过64%的代码-个人题解)
算法