Given A string s, partition s such that every substring of the partition are a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab" ,
Return
[ ["AA", "B"], ["A", "a", "B"] ]
Ideas:
Backtracking, but not conventional backtracking, because the size of the solution vector is uncertain and needs to be judged dynamically. Below is the code that I write, only uses 19ms very fast, oneself quite satisfied.
Feel: Before the DP for the minimum cut a few knives so that all parts are palindrome, and this is a bit like. Think that all the most is to use DP, all the solution is to use backtracking.
classSolution { Public: Vector<vector<string>> partition (strings) {vector<vector<string>>ans; if(S.empty ())returnans; Vector<vector<BOOL>> Ispalindrome (S.length (), vector<BOOL> (S.length (),false)); Vector<vector<int>> S (S.length (), vector<int> (2,0));//Each depth candidate range is recorded using the subscript range. intK =0; Vector<string>X; while(k >=0) { while(k >=0&& s[k][1] < S.length ())//The current depth judgment is completed by the end of the current range subscript to reach the end of S { inti = s[k][0];//the starting subscript for the current depth judgment position intj = s[k][1];//The end subscript of the current depth judgment position if(S[i] = = S[j] && (J-i <2|| ispalindrome[i+1][j-1]))//whether the sub-judgment is a palindrome, each use of historical information{Ispalindrome[i][j]=true; while(X.size () >= k +1)//x length is not fixed, so there will be the last time to solve the value, we need to put the extra part of the popup!! Special attention{x.pop_back (); } x.push_back (S.substr (i, J-i +1)); s[k][1]++; if(s[k][1] <s.length ()) {k++; s[k][0] = s[k-1][1]; s[k][1] = s[k-1][1]; } Else{ans.push_back (X); K--; } } Else{s[k][1]++; }} k--; } returnans; }};
"Leetcode" palindrome Partitioniong (middle) (*^__^*)