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);
            }
        }
    }
}
相关推荐
Swift社区1 天前
LeetCode 394. 字符串解码(Decode String)
算法·leetcode·职场和发展
tt5555555555551 天前
LeetCode进阶算法题解详解
算法·leetcode·职场和发展
让我们一起加油好吗1 天前
【基础算法】DFS中的剪枝与优化
算法·深度优先·剪枝
Q741_1471 天前
C++ 模拟题 力扣495. 提莫攻击 题解 每日一题
c++·算法·leetcode·模拟
我命由我123451 天前
Excel - Excel 列出一列中所有不重复数据
经验分享·学习·职场和发展·word·powerpoint·excel·职场发展
Felven1 天前
A. Be Positive
算法
小O的算法实验室1 天前
2026年COR SCI2区,自适应K-means和强化学习RL算法+有效疫苗分配问题,深度解析+性能实测,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
青岛少儿编程-王老师1 天前
CCF编程能力等级认证GESP—C++7级—20250927
数据结构·c++·算法
夏鹏今天学习了吗1 天前
【LeetCode热题100(39/100)】对称二叉树
算法·leetcode·职场和发展
天选之女wow1 天前
【代码随想录算法训练营——Day34】动态规划——416.分割等和子集
算法·leetcode·动态规划