java:
package leetcode15.PalindromePartitioning;
import java.util.ArrayList;
import java.util.Hashtable;
public class Solution {
public static void main(String[]args){
String s="aab";
System.out.print(partition(s));
}
public static ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> ret=new ArrayList<ArrayList<String>>();
ArrayList<String> al=new ArrayList<String>();
Hashtable<String,Boolean> ht=new Hashtable<String,Boolean>();
DFS(s,0,ht,ret,al);//DFS
return ret;
}
public static void DFS(String s,int start,Hashtable<String,Boolean> ht,ArrayList<ArrayList<String>> ret,ArrayList<String > al){
if(start==s.length()){// you can leave DFS from here
ret.add(new ArrayList<String>(al));
return;
}
for(int i=start;i<s.length();i++){
boolean isPalindrome=false;//the flag
String substr=s.substring(start,i+1);//??
if(ht.get(substr)!=null){
isPalindrome=ht.get(substr);
}else{
isPalindrome=checkPalindrome(substr);
ht.put(substr, isPalindrome);
}
if(isPalindrome){
al.add(substr);
DFS(s,i+1,ht,ret,al);
al.remove(al.size()-1);
}
}
}
public static boolean checkPalindrome(String s){
if(s.length() == 0){
return true;
}
for(int i=0; i<=s.length()/2; i++){
if(s.charAt(i) != s.charAt(s.length()-1-i)){
return false;
}
}
return true;
}
}
总结:DFS的使用,与BFS一样 应掌握