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,即已经划分完所有的字串,则将当前路径加入结果集
  • 判断回文串,可以通过记忆化搜索,fij 用于记录当前状态是否判断过
    • 其中 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);
    }
};
相关推荐
JieE2127 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
JieE2121 天前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack202 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树2 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2122 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2122 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术2 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦3 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050733 天前
(一)小红的数组操作
算法·编程语言