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

一、多维递归 -> 回溯

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
相关推荐
醒过来摸鱼7 小时前
Java classloader
java·开发语言·python
superman超哥7 小时前
仓颉语言中元组的使用:深度剖析与工程实践
c语言·开发语言·c++·python·仓颉
小鸡吃米…7 小时前
Python - 继承
开发语言·python
祁思妙想8 小时前
Python中的FastAPI框架的设计特点和性能优势
开发语言·python·fastapi
LYFlied8 小时前
【每日算法】LeetCode 153. 寻找旋转排序数组中的最小值
数据结构·算法·leetcode·面试·职场和发展
唐装鼠8 小时前
rust自动调用Deref(deepseek)
开发语言·算法·rust
Dingdangcat868 小时前
反恐精英角色识别与定位-基于改进的boxinst_r101_fpn_ms-90k_coco模型实现
python
世界唯一最大变量8 小时前
利用自定义积分公式,目前可以求出所有1元方程和1元积分的近似值
python
写代码的【黑咖啡】8 小时前
深入理解 Python 中的模块(Module)
开发语言·python
ytttr8739 小时前
MATLAB基于LDA的人脸识别算法实现(ORL数据库)
数据库·算法·matlab