企业网站建设与推广,北京建网站需要多少钱,南京网页设计照片,1688货源网问题描述 给你一个字符串 s#xff0c;请你将 s 分割成一些子串#xff0c;使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
输入示例
s aab输出示例
[[a,a,b],[…问题描述 给你一个字符串 s请你将 s 分割成一些子串使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
输入示例
s aab输出示例
[[a,a,b],[aa,b]]解题思路 我们使用回溯、深度优先遍历的思想使用 ans 记录路径使用 ret 记录路径组合结果使用 f 数组记录是否回文使用 n 记录字符串总数量。以下为核心递归逻辑i 表示分割的开始位置
如果 in表示已经分割到结尾则将路径结果 ans 放入 ret。否则从 i 开始遍历分割如果回文将从 i 到 j 的子串放入路径继续从下一个位置开始分割递归执行回溯过程
解题代码
class Solution {boolean[][] f;ListListString ret new ArrayList();ListString ans new ArrayList();int n;public ListListString 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 i1; j n; j) {f[i][j] (s.charAt(i) s.charAt(j)) f[i1][j-1];}}dfs(s, 0);return ret;}public void dfs(String s, int i) {if(i n) {ret.add(new ArrayListString(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);}}}
}