题目
字符串分割为回文
代码
public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> ans = new ArrayList<List<String>>();
List<String> temp = new ArrayList<String>();
useme(s,0,ans,temp);
return ans;
}
public void useme(String s, int startIndex, List<List<String>> ans,List<String> temp){
int n = s.length();
if(startIndex>=n){
ans.add(new ArrayList<String>(temp));
return;
}
for(int i=startIndex;i<n;i++){
if(isPa(s,startIndex,i)){
temp.add(s.substring(startIndex,i+1));
useme(s,i+1,ans,temp);
temp.remove(temp.size()-1);
}
}
}
public boolean isPa(String s, int start,int end){
while(start<end){
char c1 = s.charAt(start);
char c2 = s.charAt(end);
if(c1!=c2){
return false;
}
start++;
end--;
}
return true;
}
}
思路
DFS,不需要特别的技巧。