131. 分割回文串
题目描述
输入一个字符串 s。把它从左到右切成若干个非空的连续片段,要求每个片段都是回文串,即正读反读相同。
每种切法写成片段按原顺序组成的列表。返回所有不同的切法,切法之间的顺序不限。
示例 1
输入:s = "aab" 输出:[["a","a","b"],["aa","b"]]
解释:可以切成 a|a|b,也可以切成 aa|b。
示例 2
输入:s = "a" 输出:[["a"]]
解释:只有一种切法。
数据范围
1 <= s.length <= 16s只含小写英文字母。
解题思路:回溯并现场判回文
枚举回文前缀并回溯。
为什么正确
path 中每段都是回文。
复杂度分析
时间 O(n·n·2ⁿ),额外空间 O(n)。
易错点
注意边界条件并在回溯或弹出后恢复状态。
参考代码
Python、Java、C++、Go、JavaScript、TypeScript 六种语言,逻辑一致。
class Solution:
def partition(self,s):
out=[];p=[]
def f(i):
if i==len(s):out.append(p[:]);return
for j in range(i,len(s)):
x=s[i:j+1]
if x==x[::-1]:p.append(x);f(j+1);p.pop()
f(0);return outclass Solution {
private List<List<String>> out = new ArrayList<>();
private List<String> p = new ArrayList<>();
private String s;
public List<List<String>> partition(String s) {
this.s = s;
f(0); return out;
}
private void f(int i) {
if (i == s.length()) { out.add(new ArrayList<>(p)); return; }
for (int j = i; j < s.length(); j++) {
String x = s.substring(i, j + 1);
if (x.equals(new StringBuilder(x).reverse().toString())) { p.add(x); f(j + 1); p.remove(p.size() - 1); }
}
}
}class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> out; vector<string> p;
function<void(int)> f = [&](int i) {
if (i == s.size()) { out.push_back(p); return; }
for (int j = i; j < s.size(); j++) {
string x = s.substr(i, j - i + 1);
if (x == string(x.rbegin(), x.rend())) { p.push_back(x); f(j + 1); p.pop_back(); }
}
};
f(0); return out;
}
};func partition(s string) [][]string {
out := [][]string{}; p := []string{}
var f func(i int)
f = func(i int) {
if i == len(s) { out = append(out, append([]string{}, p...)); return }
for j := i; j < len(s); j++ {
x := s[i : j+1]
if x == reverse(x) { p = append(p, x); f(j + 1); p = p[:len(p)-1] }
}
}
f(0); return out
}
func reverse(x string) string {
b := []byte(x)
for l, r := 0, len(b)-1; l < r; l, r = l+1, r-1 {
b[l], b[r] = b[r], b[l]
}
return string(b)
}var partition = function(s) {
const out = [], p = [];
const f = (i) => {
if (i === s.length) { out.push([...p]); return; }
for (let j = i; j < s.length; j++) {
const x = s.slice(i, j + 1);
if (x === [...x].reverse().join('')) { p.push(x); f(j + 1); p.pop(); }
}
};
f(0); return out;
};function partition(s: string): string[][] {
const out: string[][] = [], p: string[] = [];
const f = (i: number): void => {
if (i === s.length) { out.push([...p]); return; }
for (let j = i; j < s.length; j++) {
const x = s.slice(i, j + 1);
if (x === [...x].reverse().join('')) { p.push(x); f(j + 1); p.pop(); }
}
};
f(0); return out;
};其他解法
现场判回文不占额外空间但会重复判断;预处理用 O(n²) 空间把每次判断降到 O(1)。
解法 2:动态规划预处理+回溯 时间 O(n·2ⁿ),空间 O(n²)
先用动态规划求出 pal[i][j]:s[i..j] 是回文当且仅当 s[i] == s[j] 且 pal[i+1][j-1] 为真。i 从右向左、j 从左向右填表。回溯时只枚举 pal[i][j] 为真的切分点,O(1) 判断。
避免了回溯中反复判断同一子串,字符串长时更快。需要 O(n²) 的表。
class Solution:
def partition(self, s):
n = len(s)
pal = [[True] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
pal[i][j] = s[i] == s[j] and pal[i + 1][j - 1]
out, path = [], []
def dfs(i):
if i == n:
out.append(path[:])
return
for j in range(i, n):
if pal[i][j]:
path.append(s[i:j + 1])
dfs(j + 1)
path.pop()
dfs(0)
return outclass Solution {
private boolean[][] pal;
private List<List<String>> out = new ArrayList<>();
private List<String> path = new ArrayList<>();
private String s;
public List<List<String>> partition(String s) {
this.s = s;
int n = s.length();
pal = new boolean[n][n];
for (int i = n - 1; i >= 0; i--) {
pal[i][i] = true;
for (int j = i + 1; j < n; j++) {
pal[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 2 || pal[i + 1][j - 1]);
}
}
dfs(0);
return out;
}
private void dfs(int i) {
int n = s.length();
if (i == n) {
out.add(new ArrayList<>(path));
return;
}
for (int j = i; j < n; j++) {
if (pal[i][j]) {
path.add(s.substring(i, j + 1));
dfs(j + 1);
path.remove(path.size() - 1);
}
}
}
}class Solution {
vector<vector<bool>> pal;
vector<vector<string>> out;
vector<string> path;
string s;
void dfs(int i) {
int n = s.size();
if (i == n) {
out.push_back(path);
return;
}
for (int j = i; j < n; j++) {
if (pal[i][j]) {
path.push_back(s.substr(i, j - i + 1));
dfs(j + 1);
path.pop_back();
}
}
}
public:
vector<vector<string>> partition(string s) {
this->s = s;
int n = s.size();
pal.assign(n, vector<bool>(n, true));
for (int i = n - 1; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
pal[i][j] = s[i] == s[j] && pal[i + 1][j - 1];
}
}
out.clear();
path.clear();
dfs(0);
return out;
}
};func partition(s string) [][]string {
n := len(s)
pal := make([][]bool, n)
for i := range pal {
pal[i] = make([]bool, n)
for j := range pal[i] {
pal[i][j] = true
}
}
for i := n - 1; i >= 0; i-- {
for j := i + 1; j < n; j++ {
pal[i][j] = s[i] == s[j] && pal[i+1][j-1]
}
}
out := [][]string{}
path := []string{}
var dfs func(i int)
dfs = func(i int) {
if i == n {
out = append(out, append([]string{}, path...))
return
}
for j := i; j < n; j++ {
if pal[i][j] {
path = append(path, s[i:j+1])
dfs(j + 1)
path = path[:len(path)-1]
}
}
}
dfs(0)
return out
}var partition = function(s) {
const n = s.length;
const pal = Array.from({ length: n }, () => new Array(n).fill(true));
for (let i = n - 1; i >= 0; i--) {
for (let j = i + 1; j < n; j++) {
pal[i][j] = s[i] === s[j] && pal[i + 1][j - 1];
}
}
const out = [], path = [];
const dfs = (i) => {
if (i === n) {
out.push([...path]);
return;
}
for (let j = i; j < n; j++) {
if (pal[i][j]) {
path.push(s.slice(i, j + 1));
dfs(j + 1);
path.pop();
}
}
};
dfs(0);
return out;
};function partition(s: string): string[][] {
const n = s.length;
const pal: boolean[][] = Array.from({ length: n }, () => new Array(n).fill(true));
for (let i = n - 1; i >= 0; i--) {
for (let j = i + 1; j < n; j++) {
pal[i][j] = s[i] === s[j] && pal[i + 1][j - 1];
}
}
const out: string[][] = [], path: string[] = [];
const dfs = (i: number): void => {
if (i === n) {
out.push([...path]);
return;
}
for (let j = i; j < n; j++) {
if (pal[i][j]) {
path.push(s.slice(i, j + 1));
dfs(j + 1);
path.pop();
}
}
};
dfs(0);
return out;
}