Palindrome Partitioning
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"] ]
In order to accelerate the operation, the dynamic programming can be used to find the position of the substring satisfying the palindrome palindrome[i][j] represents the string, S[i,i+1,......, j] is a palindrome can have the following recursive formula: if (I==J) palindrome[i][j]=true ; if (i-j=1) palindrome[i][j]=s[i]==s[j];if (i-j>1) palindrome[i][j]=palindrome[i+1][j-1]&&s[i]==s[j] After getting the palindrome table, we use backtracking to get all the substrings
1 classSolution {2 Public:3 4Vector<vector <string> >Res;5 6vector<vector<BOOL> >palindrome;7 strings;8 intN;9 Tenvector<vector<string>> partition (strings) { One A This->s=s; - This->n=s.length (); - thevector<vector<BOOL> > Palindrome (n,vector<BOOL>(n)); - Getpalindrome (palindrome); - This->palindrome=palindrome; - +Vector <string>tmp; -Getpartition (0, TMP); + A returnRes; at } - - //backtracking to get substrings - voidGetpartition (intstart,vector<string>tmp) - { - in if(start==N) - { to Res.push_back (TMP); + return; - } the * for(inti=start;i<n;i++) $ {Panax Notoginseng if(Palindrome[start][i]) - { theTmp.push_back (S.substr (start,i-start+1)); +Getpartition (i+1, TMP); A Tmp.pop_back (); the } + } - } $ $ - - voidGetpalindrome (vector<vector<BOOL> > &palindrome) the { - intstartindex=0;Wuyi intendindex=n-1; the - for(inti=n-1; i>=0; i--) Wu { - for(intj=i;j<n;j++) About { $ if(i==j) - { -palindrome[i][j]=true; - } A Else if(j-i==1) + { thePalindrome[i][j]= (s[i]==s[j]); - } $ Else if(j-i>1) the { thePalindrome[i][j]= (s[i]==s[j]&&palindrome[i+1][j-1]); the } the } - } in } the};
"Leetcode" palindrome partitioning