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"] ]
列出字符串分解的题基本都是DFS,本题是找出s所有合数的分解,故i=start
在permutation那题中,需要列出所有可能的排列,每次递归时是从i=0开始
1 public class Solution { 2 public ArrayList<ArrayList<String>> partition(String s) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>(); 6 ArrayList<String> output = new ArrayList<String>(); 7 int depth = 0, len = s.length(); 8 9 palinPartition(s, 0, len, output, result); 10 return result; 11 } 12 13 public void palinPartition(String s, int start, int len, ArrayList<String> output, 14 ArrayList<ArrayList<String>> result){ 15 if(start == len){ 16 ArrayList<String> tmp = new ArrayList<String>(); 17 tmp.addAll(output); 18 result.add(tmp); 19 return; 20 } 21 22 for(int i = start; i < len; i++){ 23 if(isPalindrome(s, start, i)){ 24 output.add(s.substring(start, i + 1)); 25 palinPartition(s, i + 1, len, output, result); 26 output.remove(output.size() - 1); 27 } 28 } 29 30 } 31 32 public boolean isPalindrome(String s, int start, int end){ 33 while(start < end){ 34 if(s.charAt(start) != s.charAt(end)){ 35 return false; 36 } 37 start ++; 38 end --; 39 } 40 41 return true; 42 } 43 }