[Question]
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"] ]
Question]
Given a string S, Division of S is required. After division, each substring is a return string.
All division conditions must be returned.
[Idea]
The intuitive idea is to use layer-by-layer recursion. First, determine the first vertex, then the second vertex, then the third vertex, and so on. This method has a very high time complexity.
This question uses DP: calculate whether the substring between the two positions I and J is a return string, which is represented by ispalindrome [I] [J.
[Code]
Class solution {public: void getpartition (vector <string> & result, vector <string> & splits, int start, string & S, vector <vector <bool> & ispal) {// spits-split result, start-current split start position if (START = S. length () {vector <string> newsplits = splits; result. push_back (newsplits); return;} For (INT end = start; end <S. length (); End ++) {If (ispal [start] [end]) {splits. push_back (S. substr (START, end-start + 1); getpartition (result, splits, end + 1, S, ispal); splits. pop_back () ;}}vector <vector <string> partition (string s) {vector <string> result; int Len = S. length (); If (LEN = 0) return result; vector <bool> ispal (Len, vector <bool> (Len, false )); // initialize ispal [I] [I] = true; For (INT I = 0; I <Len; I ++) ispal [I] [I] = true; // initialize a substring consisting of two adjacent characters for (INT I = 0; I <len-1; I ++) if (s [I] = s [I + 1]) ispal [I] [I + 1] = true; // determine the position of other I <j For (INT I = len-3; I> = 0; I --) for (Int J = I + 2; j <Len; j ++) ispal [I] [J] = (s [I] = s [J]) & ispal [I + 1] [J-1]; // determine all combinations of vector <string> splits; getpartition (result, splits, 0, S, ispal ); return result ;}};