First, the topic
1, examining
2. Analysis
Give a string, divide it into sub-strings, make its substring all palindrome, ask all the segmentation.
Second, the answer
1, Ideas:
Method One,
Recursive method is used for segmentation.
①, recursive, determine whether the current split substring is a palindrome, if, store the substring, and split the string, continue to recursion the remaining substrings;
②, recursive jump condition is: the character of the current string cut subscript i >= the length of the string;
PublicList<list<string>>partition (String s) {List<List<String>> resultlist =NewArraylist<>(); BackTrack (Resultlist,NewArraylist<string> (), s, 0); returnresultlist; } Private voidBackTrack (list<list<string>> resultlist, arraylist<string> curlist, String s,inti) {if(Curlist.size () > 0 && i >=s.length ()) {Resultlist.add (NewArraylist<string>(curlist)); return; } for(intj = i; J < S.length (); J + +) { if(Ispalindrome (S, I, J)) {Curlist.add (S.substring (i, J+ 1)); BackTrack (Resultlist, Curlist, S, J+ 1); Curlist.remove (Curlist.size ()+ W); } } } Private BooleanIspalindrome (String S,intLintr) { while(L <r) {if(S.charat (l++)! = S.charat (r--)) return false; } return true; }
Method Two,
Implemented with DP + DFS.
The use of a dynamic array of DP Records is a palindrome, in lieu of each recursive for palindrome judgment. DP[I][J] = true: Indicates that the string from subscript I to subscript j in S is a palindrome.
Then recursive for the DFS traversal, the s of all the Cut palindrome string records.
PublicList<list<string>>Partition2 (String s) {List<List<String>> resultlist =NewArraylist<>(); Boolean[] DP =New Boolean[S.length ()][s.length ()]; for(inti = 0; I < s.length (); i++) { for(intj = 0; J <= I; J + +) { if(S.charat (j) = = S.charat (i) && (i-j <= 2 | | dp[j+1][i-1])) {Dp[j][i]=true; }}} partitionhelper (Resultlist,NewArraylist<string> (), DP, S, 0); returnresultlist; } Private voidPartitionhelper (list<list<string>> resultlist, arraylist<string>ArrayList,Boolean[] DP, String s,inti) {if(Arraylist.size () > 0 && i >=s.length ()) {Resultlist.add (NewArraylist<>(arrayList)); return; } for(intj = i; J < S.length (); J + +) { if(Dp[i][j]) {Arraylist.add (S.substring (i, J+ 1)); Partitionhelper (Resultlist, ArrayList, DP, S, J+ 1); Arraylist.remove (Arraylist.size ()-1); } } }
131. Palindrome partitioning