LeetCode131. 分割回文串(2024冬季每日一题 4)

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

示例 1:

输入:s = "aab"

输出:[["a","a","b"],["aa","b"]]

示例 2:

输入:s = "a"

输出:[["a"]]

提示:

1 <= s.length <= 16

s 仅由小写英文字母组成


思路: dfs + 记忆化搜索

  • dfs 递归当前 start 下标开始的字串能如何划分,枚举其右边界
  • 如果当前字串是回文串,则将当前字串加入当前dfs路径,dfs 继续递归剩余的字串
  • 当前路径递归完,遍历下个边界时,需要回溯,删除路径列表中之前的字串
  • 如果递归到 start==n,即已经划分完所有的字串,则将当前路径加入结果集
  • 判断回文串,可以通过记忆化搜索,f[i][j] 用于记录当前状态是否判断过
    • 其中 1 代表是回文串,-1 代表不是,0 代表还没有搜索过
cpp 复制代码
class Solution {
public:
    vector<vector<string>> res;
    vector<string> ans;
	// 1 代表是回文串,-1 代表不是,0 代表还没有搜索过
    int f[20][20];
    int n;
    vector<vector<string>> partition(string s) {
        n = s.size();
        dfs(s, 0);
        return res;
    }
    void dfs(string &s, int start){
        if(start == n){
            res.push_back(ans);
            return;
        }
        for(int i = start; i < n; i++){
            if(is_fn(s, start, i) == 1){
                ans.push_back(s.substr(start, i - start + 1));
                dfs(s, i + 1);
                ans.pop_back();
            }
        }
    }

    int is_fn(string &s, int l, int r){
        if(l >= r) return f[l][r] = 1;
        if(f[l][r] == 1 || f[l][r] == -1)
            return f[l][r];

        return f[l][r] = ((s[l] == s[r]) ? is_fn(s, l + 1, r - 1): -1);
    }
};
相关推荐
YC运维1 天前
Ansible题目全解析与答案
java·算法·ansible
小欣加油1 天前
leetcode 912 排序数组(归并排序)
数据结构·c++·算法·leetcode·排序算法
山河君1 天前
webrtc之高通滤波——HighPassFilter源码及原理分析
算法·音视频·webrtc·信号处理
星辰大海的精灵1 天前
SpringBoot与Quartz整合,实现订单自动取消功能
java·后端·算法
data myth1 天前
力扣1210. 穿过迷宫的最少移动次数 详解
算法·leetcode·职场和发展
惯导马工1 天前
【论文导读】AI-Assisted Fatigue and Stamina Control for Performance Sports on IMU-Gene
深度学习·算法
沐怡旸1 天前
【算法--链表】109.有序链表转换二叉搜索树--通俗讲解
算法·面试
CoovallyAIHub1 天前
推理提速一倍!SegDT:轻量化扩散 Transformer,医学图像分割的技术跨越
深度学习·算法·计算机视觉
CoovallyAIHub1 天前
无人机方案如何让桥梁监测更安全、更智能?融合RTK与超高分辨率成像,优于毫米精度
深度学习·算法·计算机视觉
lingran__1 天前
C语言制作扫雷游戏(拓展版赋源码)
c语言·算法·游戏