题目:
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
示例 1:
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]
过程图来自代码随想录:
![](https://i-blog.csdnimg.cn/blog_migrate/25a103cd6f14497295f8834b52c7adc1.jpeg)
记录难点:
利用startIndex和i作为分割线:要清楚startIndex和i两者各自是怎么变化的,startIndex它的变化来自递归(即纵向遍历时startIndex开始变化),而i的变化来自for循环(即横向遍历时i开始变化),所以在进行分割时,startIndex作为起始,而i作为结尾。
当出现一次分割结果不是回文串时,直接跳过该循环(不会进入递归):因为我们要的是分割的所有字串都是回文串,当出现一种情况不是回文串是就已经不符合要求。如:abab,当我们开始判断a|ba|b
,startIndex指向b,i指向第二个a,发现ba并不是回文串,就直接跳过当前循环,开始判断bab 。
在startIndex >= s.length()时开始收集结果:从在上一步我们可以知道,能进入递归的说明之前分割的子串都是回文子串,( 不是回文子串的我们直接跳出循环,不会进入递归)所以我们只需要判断startIndex是否已经遍历到s的末尾,startIndex到末尾说明我们已经找到符合要求的一组分割方案,直接加入到result中就行。
Java代码:
class Solution {
List<List<String>> result = new ArrayList<List<String>>();
List<String> list = new ArrayList<String>();
public List<List<String>> partition(String s) {
backtracking(s,0);
return result;
}
public void backtracking(String s,int startIndex){
if(startIndex >= s.length()){
result.add(new ArrayList<String>(list));
return;
}
for(int i = startIndex; i < s.length(); i++){
//判断是不是回文串
if(Palindromes(s,startIndex,i)){
list.add(s.substring(startIndex,i + 1));
}else{
continue;
}
backtracking(s,i + 1);
//回溯
list.remove(list.size() - 1);
}
}
public boolean Palindromes(String str,int start,int end){
for(int i = start,j = end; i < j; i++,j--){
if(str.charAt(i) != str.charAt(j)){
return false;
}
}
return true;
}
}