Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab"
,
Return
[ ["aa","b"], ["a","a","b"] ]
思路: 很容易想到用回溯法,因为要遍历所有可能的情况,每次遍历如果达到length的长度,就返回,这里需要注意,每次遍历总能够满足条件,因为总能把最后一个字符单独作为一个palindrome。搜索的时候不断得add满足条件的substring,回溯的时候再将其删除,寻找其他线路上的palindrome。
public class Solution {
public boolean is_Palindrome(String s){
int start = 0;
int end = s.length() - 1;
while(start < end){
if(s.charAt(start) == s.charAt(end)){
start++;
end--;
}else{
return false;
}
}
return true;
}
public void dfs(ArrayList<ArrayList<String>> result, ArrayList<String> path, String s, int index){
if(index == s.length()){
result.add(new ArrayList<String>(path));
return;
}
for(int i = index+1; i <= s.length(); i++){
String prefix = s.substring(index, i);
if(!is_Palindrome(prefix))
continue;
path.add(prefix);
dfs(result, path, s, i);
path.remove(path.size() - 1);
}
}
public ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
if(s == null)
return result;
ArrayList<String> path = new ArrayList<String>();
dfs(result, path, s, 0);
return result;
}
}