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);
            }
        }
    }
}
相关推荐
hqyjzsb23 分钟前
法律 Prompt 干货:搭建合同审查提示词要包含哪些要素
开发语言·人工智能·python·职场和发展·数据分析·prompt·业界资讯
Discipline102943 分钟前
尼泊尔河流流量:天气驱动的预测与高流量风险
人工智能·算法
XuCoder1 小时前
改一个数,右边全得重算,这题怎么扛住两万次查询
算法
小羊没烦恼!1 小时前
在Scrum中实施敏捷建模
java·开发语言·windows·算法·c#
weixin_307779131 小时前
基于睿擎工业开发平台的预训练视觉模型轻量化适配与低代码部署优化
开发语言·算法
hold?fish:palm2 小时前
45 二叉树的右视图
开发语言·c++·算法
粤鼎恒业2 小时前
惠州工厂电子料回收厂家推荐:从交接单反推筛选标准
大数据·数据库·算法·硬件架构·硬件工程·pcb工艺·材料工程
小爷毛毛(卓寿杰)3 小时前
【Agent 意图识别】输出协议、评估与置信度
人工智能·算法·大模型·prompt·大语言模型·agent
优质酸酸乳3 小时前
力扣100题之21合并两个有序链表
算法·leetcode·链表
旖旎夜光3 小时前
LeetCode 137 : 只出现一次的数字 II(位运算) —— 题解
c++·笔记·学习·算法·leetcode·力控