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);
            }
        }
    }
}
相关推荐
科学实验家13 小时前
完全背包
算法
Smoothcloud润云13 小时前
GPU租赁数据安全怎么做?
人工智能·算法·ai·aigc·gpu算力·gpu
呜喵王阿尔萨斯13 小时前
extern “C“ in C++
c语言·c++·算法
乐观勇敢坚强的老彭14 小时前
C++信奥静态数组和动态数组
数据结构·c++·算法
月光船幽幽14 小时前
呼吸孔设计重塑系统稳定性
python·科技·算法
旖旎夜光15 小时前
LeetCode 991: 坏了的计算器(贪心算法) —— 题解
数据结构·c++·算法·leetcode·贪心算法
旖旎夜光15 小时前
LeetCode 553:最优除法(贪心算法) —— 题解
数据结构·c++·算法·leetcode·贪心算法
雾喔15 小时前
算法练习7
java·数据结构·算法
过期的秋刀鱼!15 小时前
重点-偏差方差与神经网络
人工智能·深度学习·神经网络·算法·机器学习·过拟合·l2正则化