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);
            }
        }
    }
}
相关推荐
旖-旎1 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC1 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
delishcomcn2 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹2 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
雪碧聊技术3 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
CV-Climber5 小时前
检索技术的实际应用
人工智能·算法
hhzz6 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_7 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
TsingtaoAI7 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅