题目:
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例: 输入: "aab" 输出: [ ["aa","b"], ["a","a","b"] ]
题解:
切割字符串类似于组合,可以画成二叉树的形式。
步骤:
1.递归函数参数
定义全局变量path存放切割后回文的子串,res存放结果集。 (这两个参数可以放到函数参数里)
本题递归函数参数还需要startIndex,因为切割过的地方,不能重复切割,和组合问题也是保持一致的。
2.递归函数终止条件
从树形结构的图中可以看出:切割线切到了字符串最后面,说明找到了一种切割方法,此时就是本层递归的终止终止条件。
3.单层搜索的逻辑
首先判断这个子串是不是回文,如果是回文,就加入path
中,path用来记录切割过的回文子串。
判断回文:
public boolean isPalindrome(String s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
完整代码:
class Solution {
LinkedList<String> path = new LinkedList<>();
List<List<String>> res = new LinkedList<>();
public List<List<String>> partition(String s) {
backtracking(s, 0);
return res;
}
public void backtracking(String s, int startIndex) {
if (startIndex == s.length()) {
res.add(new LinkedList<>(path));
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (isPalindrome(s, startIndex, i)) { //注意isPalindrome函数后两个参数是什么,检查的是同一个树层的回文情况
String str = s.substring(startIndex, i + 1); //substring左闭右开
path.add(str);
} else {
continue;
}
backtracking(s, i + 1);
path.remove(path.size() - 1);
}
}
public boolean isPalindrome(String s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
}
参考:代码随想录