Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: “aab”
Output:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]
131题目要求回文 并找出所有可能的分割
一看到找出所有则想到用backtracking
有个猜想说明我对回溯法还不是很理解
如果是要找出所有结合排列组合 需要设定一个终止条件?
如果要找出子集 则不需要终止条件?
尤其是到了这道题,
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
backTracking(s,res,new ArrayList<String>(),0);
return res;
}
public void backTracking(String s, List<List<String>> res,
List<String> list,int start){
if( start == s.length()){
res.add( new ArrayList<>(list));
return;
}
for(int i = start; i< s.length();i++){
if(isPalindrome(s,start,i)){// 如果不构成回文,则不进行下一次递归
list.add(s.substring(start,i+1));
backTracking(s,res,list,i+1);//如果[i,j]中字符构成回文,那么进行下一次递归,判断j+1之后字符是否构成回文
list.remove(list.size()-1);
}
}
}
private boolean isPalindrome(String s, int start, int end){
while(start<end){
if(s.charAt(start++) != s.charAt(end-- ))return false;
}
return true;
}
}```