131. 分割回文串 - 力扣(LeetCode)

问题描述

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

回文串 是正着读和反着读都一样的字符串。

输入示例

bash 复制代码
s = "aab"

输出示例

bash 复制代码
[["a","a","b"],["aa","b"]]

解题思路

我们使用回溯、深度优先遍历的思想,使用 ans 记录路径,使用 ret 记录路径组合结果,使用 f 数组记录是否回文,使用 n 记录字符串总数量。以下为核心递归逻辑,i 表示分割的开始位置:

  • 如果 i==n,表示已经分割到结尾,则将路径结果 ans 放入 ret。
  • 否则从 i 开始遍历分割,如果回文,将从 i 到 j 的子串放入路径
  • 继续从下一个位置开始分割递归
  • 执行回溯过程

解题代码

java 复制代码
class Solution {
    boolean[][] f;
    List<List<String>> ret = new ArrayList<>();
    List<String> ans = new ArrayList<>();
    int n;

    public List<List<String>> partition(String s) {
        n = s.length();
        f = new boolean[n][n];
        for(int i = 0; i < n; i++) {
            Arrays.fill(f[i], true);
        }
        for(int i = n-1; i >= 0; i--) {
            for(int j = i+1; j < n; j++) {
                f[i][j] = (s.charAt(i) == s.charAt(j)) && f[i+1][j-1];
            }
        }
        dfs(s, 0);
        return ret;
    }

    public void dfs(String s, int i) {
        if(i == n) {
            ret.add(new ArrayList<String>(ans));
            return;
        }
        for(int j = i; j < n; j++) {
            if(f[i][j]) {
                ans.add(s.substring(i, j + 1));
                dfs(s, j + 1);
                ans.remove(ans.size() - 1);
            }
        }
    }
}
相关推荐
努力学算法的蒟蒻3 小时前
day61(1.20)——leetcode面试经典150
面试·职场和发展
夏鹏今天学习了吗3 小时前
【LeetCode热题100(87/100)】最小路径和
算法·leetcode·职场和发展
哈哈不让取名字3 小时前
基于C++的爬虫框架
开发语言·c++·算法
Lips6115 小时前
2026.1.20力扣刷题笔记
笔记·算法·leetcode
2501_941329725 小时前
YOLOv8-LADH马匹检测识别算法详解与实现
算法·yolo·目标跟踪
洛生&5 小时前
Planets Queries II(倍增,基环内向森林)
算法
小郭团队6 小时前
1_6_五段式SVPWM (传统算法反正切+DPWM2)算法理论与 MATLAB 实现详解
嵌入式硬件·算法·matlab·dsp开发
小郭团队6 小时前
1_7_五段式SVPWM (传统算法反正切+DPWM3)算法理论与 MATLAB 实现详解
开发语言·嵌入式硬件·算法·matlab·dsp开发
鱼跃鹰飞6 小时前
Leetcode347:前K个高频元素
数据结构·算法·leetcode·面试
bybitq6 小时前
LeetCode236-二叉树的最近公共祖先(LCA)问题详解-C++
算法·深度优先