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"] ]
思路:因为要列举所有可能,所以考虑回溯法。这道题没做出来主要因为两点:
1.判断结束条件,没有考虑到当已探索长度大于字符串时要保存结果并返回。
2.回溯,不知道删除临时栈的最新结果来实现回溯。
class Solution {
List<String> res;
List<List<String>> ans;
public void recursive(String s,int len){
if(len >= s.length() && res.size() > 0){
List<String> l = new ArrayList<String>(res);
ans.add(l);
}
for(int i = len ; i < s.length() ; i++){
if(isPalindrome(len,i,s)){
res.add(s.substring(len,i+1));
recursive(s,i+1);
res.remove(res.size()-1);
}
}
}
public boolean isPalindrome(int left,int right,String s){
int l = left;
int r = right;
while(l <= r && s.charAt(l) == s.charAt(r) ){
l++;
r--;
}
if(l <= r) return false;
return true;
}
public List<List<String>> partition(String s) {
res = new ArrayList<String>();
ans = new ArrayList<List<String>>();
recursive(s,0);
return ans;
}
}