131.分割回文串
思路
前面回溯联系的都是组合,每次取一个字符出来进行拼接。
回溯分割做法,难点在于什么情况下终止回溯。如何分割,每次怎么取。
先解决第一个问题,按照题目意思,需要将s分割成多个回文串,那么终止条件则是找到了分割的办法,且所有子串为回文串。
如何分割,按照回溯模板,在for循环中进行思考。不同于组合for循环的i下标用于每次取出一个字符用于当前位置的组合,在分割中i下标扮演着分割线的作用,负责将起始位置到i的字符分割出来。
按照题目意思,分割出来的子串为回文串,那么添加,递归查找后续子串内的回文串分割方法;否则当前分割线后移(i++),直到出现回文串。
分割回溯所注意的是,串要分割成几串就需要几个分割线,所以最后一个分割线一定在串的末尾,也即终止条件只需遍历完整s,分割线位置出现在末尾的时候。
代码
class Solution {
List<List<String>> result =new ArrayList<>();
Deque<String> deque=new LinkedList<>();
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<>(deque));
return;
}
for (int i=startIndex;i<s.length();i++){
if (isPal(s, startIndex, i)) {
String str=s.substring(startIndex,i+1);
deque.addLast(str);
}else {
continue;
}
backTracking(s,i+1);
deque.removeLast();
}
}
public boolean isPal(String str,int start,int end){
while (start<=end){
if (str.charAt(start)!=str.charAt(end)) return false;
start++;
end--;
}
return true;
}
}