回溯(子集型):分割回文串

一、多维递归 -> 回溯

1.1:17. 电话号码的字母组合(力扣hot100)

  • 代码:
python 复制代码
mapping = ["","", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        n = len(digits)
        if n == 0:
            return []
        res = []
        path = [""] * n
        def dfs(i):                              # 一个子问题的具体细节
            if i==n:
                res.append("".join(path))
                return
            for c in mapping[int(digits[i])]:
                path[i] = c
                dfs(i+1)                       # 下一个子问题
        dfs(0)
        return res

二、子集型回溯

2.1:78. 子集

  • 代码:
python 复制代码
class Solution:
	'''
	站在输入的角度,每个数都可选或不选
	最终每个叶子就是答案
	'''
    def subsets(self, nums: List[int]) -> List[List[int]]:
        if len(nums) == 0:
            return []
        res = []
        path = []
        n = len(nums)
        def dfs(i):
            if i==n:
                res.append(path.copy())
                return
            
            dfs(i+1)                # 不选

            path.append(nums[i])    # 选
            dfs(i+1)
            path.pop()   # 记得恢复现场
            
        dfs(0)
        return res

class Solution:
    """
    站在答案的角度,第一个数选谁,第二个数选谁,...
    每个节点都是答案子集
    """
    def subsets(self, nums: List[int]) -> List[List[int]]:
        if len(nums) == 0:
            return []
        res = []
        path = []
        n = len(nums)
        def dfs(i):
            res.append(path.copy())  # 每个节点都直接添加
            if i==n:
                return
            for j in range(i, n):
                path.append(nums[j])    # 下一个数选谁
                dfs(j+1)
                path.pop()   # 记得恢复现场
            
        dfs(0)
        return res

2.2:131. 分割回文串

  • 代码:
python 复制代码
class Solution:
    """
    站在答案的角度,第一个数选谁,第二个数选谁,...
    每个节点都是答案
    """
    def partition(self, s: str) -> List[List[str]]:
        res = []
        path = []
        n = len(s)
        def dfs(i):
            if i==n:
                res.append(path.copy())  # 这里是答案包含全部字符,所以只有最后一把才记录结果
                return 
            for j in range(i, n):
                t = s[i:j+1]
                if t==t[::-1]:
                    path.append(t)
                    dfs(j+1)
                    path.pop()
        dfs(0)
        return res
相关推荐
攻城狮CSU3 小时前
类型转换汇总 之C#
java·算法·c#
小老鼠不吃猫3 小时前
C++ STL <algorithm>中泛型算法:查找、排序、修改、统计、生成
c++·算法·排序算法
白杆杆红伞伞3 小时前
01_svm_二分类
算法·支持向量机·分类
isyoungboy3 小时前
使用SVM构建光照鲁棒的颜色分类器:从特征提取到SVM
算法·机器学习·支持向量机
极客数模3 小时前
2025年MathorCup 大数据竞赛明日开赛,注意事项!论文提交规范、模板、承诺书正确使用!2025年第六届MathorCup数学应用挑战赛——大数据竞赛
大数据·python·算法·matlab·图论·比赛推荐
.小小陈.3 小时前
数据结构3:复杂度
c语言·开发语言·数据结构·笔记·学习·算法·visual studio
立志成为大牛的小牛3 小时前
数据结构——二十四、图(王道408)
数据结构·学习·程序人生·考研·算法
PieroPc3 小时前
用Python Streamlit Sqlite3 写一个简单商品管理系统
数据库·python·sqlite·streamlit
小白银子4 小时前
零基础从头教学Linux(Day 55)
java·linux·服务器·python
程序员小远4 小时前
Appium+python+unittest搭建UI自动化框架
自动化测试·软件测试·python·测试工具·ui·appium·测试用例