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);
    }
};
相关推荐
Pniubi4 小时前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表
꧁细听勿语情꧂5 小时前
直接选择排序,堆排序,冒泡排序,递归快速排序、hoare版本、挖坑法、lomuto前后指针,非递归快速排序
c语言·开发语言·数据结构·算法
俊俊几年的5 小时前
动态规划(Dynamic Programming)详解:从入门到 LeetCode Hot 100
linux·c++·算法·leetcode·嵌入式·动态规划·c
小雉系统14 小时前
BcoreOS安全通信架构:FsSession 抗算法后门安全设计
算法·安全·架构
唐墨12318 小时前
linux kernel 比较数据大小的宏定义
linux·算法
拂拉氏19 小时前
【知识讲解-题目讲解】 统计满足K约束的子字符串数量2 (滑动窗口+前缀和+二分查找+分析)
算法·前缀和·二分查找·滑动窗口
通信小呆呆1 天前
电子战抗干扰技术:当“不被干扰”成为一种系统
算法·通信·mimo·isac
笑容掩饰我的失落1 天前
区块链从小白到精通(八):从零实现一个标准 ERC-20 代币(完整可运行代码)
算法·区块链·php·智能合约·哈希算法
Severus_black1 天前
【C++初阶】Stack、Queue算法题大练兵!
c语言·c++·算法·stl