题目描述
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
输入:s = “aab”
输出:[ [ “a” , “a” , “b” ] , [ “aa” , “b” ] ]
如果有了 组合总和 系列刷题经历,此题就大同小异 ,(图片来源:)
class Solution {
List<List<String>> result = new ArrayList<>();
public List<List<String>> partition(String s) {
List<String> path = new ArrayList<>();
backtracking(path , s , 0);
return result;
}
public void backtracking(List<String> path , String s , int start){
// 如果 起始位置 已经大于 s 的 大小 , 则说明已经找到了一组分割方案
if(start >= s.length()){
result.add(new ArrayList<>(path));
return ;
}
for(int i = start ; i < s.length() ; i ++){
if(isPalindrome(s , start , i)) { // 是回文子串
// 获取 [start , i] 在 sb 中的子串
String str = s.substring(start , i + 1); // substring 方法是 左闭右开
path.add(str);
} else {
continue;
}
backtracking(path , 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;
}
}