131. 分割回文串 - 题解
题目概述
给定一个字符串 s,要求将 s 分割成若干子串,使得每个子串都是 回文串。返回所有可能的分割方案。
示例:
输入:s = "aab"
输出:[["a","a","b"], ["aa","b"]]
解题思路
核心思想:回溯算法
这道题的本质是:找到所有可能的切割方式,使得切割出的每一段都是回文串。
我们可以将其理解为一棵 决策树:
- 树的每一层代表一次切割。
- 每个节点表示当前已切割出的子串列表。
- 从当前剩余字符串的起始位置开始,尝试所有可能的切割点(即子串结束位置)。
- 只有当前切割出的子串是回文串时,才继续向下递归。
算法步骤
-
初始化:
- 一个结果列表
output,用于存放所有合法的分割方案。 - 一个当前路径列表
current,用于存放当前正在尝试的分割方案。
- 一个结果列表
-
递归函数
backtrack:- 参数 :
s:原始字符串start:当前切割的起始位置current:当前已分割出的子串列表output:结果列表
- 终止条件 :如果
start == s.length(),说明已经处理完整个字符串,将current的副本加入output。 - 递归过程 :
- 从
start开始,尝试所有可能的结束位置end(end ∈ [start+1, s.length()])。 - 取出子串
sub = s.substring(start, end)。 - 如果
sub是回文串:- 将其加入
current。 - 递归处理剩余部分
backtrack(s, end, current, output)。 - 回溯:从
current中移除sub。
- 将其加入
- 从
- 参数 :
-
判断回文串:
- 使用双指针法判断子串是否为回文。
代码实现(Java)
java
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> output = new ArrayList<>();
List<String> current = new ArrayList<>();
backtrack(s, 0, current, output);
return output;
}
private void backtrack(String s, int start, List<String> current, List<List<String>> output) {
if (start == s.length()) {
output.add(new ArrayList<>(current));
return;
}
for (int end = start + 1; end <= s.length(); end++) {
String substring = s.substring(start, end);
if (isPalindrome(substring)) {
current.add(substring);
backtrack(s, end, current, output);
current.remove(current.size() - 1);
}
}
}
private boolean isPalindrome(String str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
回溯树示例(以 "aab" 为例)
开始:start = 0, current = []
├─ 切割 "a"(回文)
│ ├─ start = 1, 切割 "a"(回文)
│ │ └─ start = 2, 切割 "b"(回文)→ 收集结果 ["a","a","b"]
│ └─ start = 1, 切割 "ab"(不是回文)→ 剪枝
├─ 切割 "aa"(回文)
│ └─ start = 2, 切割 "b"(回文)→ 收集结果 ["aa","b"]
└─ 切割 "aab"(不是回文)→ 剪枝
复杂度分析
- 时间复杂度:O(N × 2^N),最坏情况下字符串的所有子串都是回文,需要遍历所有分割方案。
- 空间复杂度 :O(N),递归调用栈的深度最多为 N,
current列表的大小也为 O(N)。
关键点总结
- 回溯框架:每一步尝试一个切割点,递归处理剩余部分,回溯时撤销选择。
- 剪枝优化:只有当前子串是回文时才继续递归,避免无效搜索。
- 结果收集 :在递归到底(即
start == s.length())时,将当前路径加入结果集。 - 回文判断:使用双指针法判断子串是否为回文,避免重复计算。
总结
本题是典型的 回溯 + 剪枝 问题,通过构建决策树来枚举所有可能的分割方式,并通过回文判断提前剪枝,有效减少了搜索空间。掌握这种"尝试-回溯"的思维模式,对解决类似组合、分割、排列问题非常有帮助。
提示:可以进一步优化,使用动态规划预处理回文判断表,将回文判断的时间复杂度降为 O(1),从而提升整体效率。