主题思想: 回溯法,好久没写,这种套路,再温习下
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> ans=new ArrayList<List<String>>();
if(s==null||s.length()==0) return ans;
backtrack(ans,new ArrayList<String>(),s);
return ans;
}
public void backtrack(List<List<String>> ans,List<String> tmp,String s){
if(s.length()==0){
ans.add(new ArrayList<String>(tmp)); //this is important 一定要用tmp去生成新的list,否则,tmp后续会被改变
return ;
}
for(int i=0;i<s.length();i++){
if(isPalindrome(s.substring(0,i+1))){
tmp.add(s.substring(0,i+1));
backtrack(ans,tmp,s.substring(i+1));
tmp.remove(tmp.size()-1); //回溯
}
}
}
public boolean isPalindrome(String s){
if(s==null) return true;
int i=0;
int j=s.length()-1;
for(;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j))return false;
}
return true;
}
}
本文深入探讨了回溯法的基本原理及其实现方式,并通过一个具体的字符串分割问题实例展示了如何使用回溯法来寻找所有可能的解决方案。文章还特别强调了在递归过程中保存中间结果的重要性。
2900

被折叠的 条评论
为什么被折叠?



