Topic
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
This problem can be solved by backtracking. Divide the string s into front and back two strings str1, str2, if STR1 is a palindrome, add partition, and then recursively str2.
Code
/**------------------------------------* Date: 2015-03-02 * SJF0115 * Title: 131.Palindrome Partitioning * URL: https://oj.leetcode.com/problems/palindrome-partitioning/* result: AC * Source: Leetcode * Blog:----------- ----------------------------**/ #include <iostream> #include <vector> #include <algorithm> using namespace STD;classSolution { Public: vector<vector<string> >Partitionstrings) { vector<string>Path vector<vector<string> >ResultintSize = S.size ();if(Size <=0){returnResult }//ifPartition (S,size,0, Path,result);returnResult }Private://s source string size source string length start split point //Path Intermediate results result end result voidPartition (stringStrintSizeintStart vector<string>&path, vector<vector<string> >&result) {//Termination conditions if(start = = size) {result.push_back (path);return; }//if stringSubstr//Split string for(inti = Start;i < Size;++i) {substr = Str.substr (start,i-start+1);//Determine if it is a palindrome string if(Ispalindrome (SUBSTR)) {Path.push_back (substr); Partition (str,size,i+1, Path,result); Path.pop_back (); }//if}//for}//Determine if the string is a palindrome BOOLIspalindrome (stringSTR) {intSize = Str.size ();if(Size = =0){return false; }//if intleft =0;intright = size-1; while(Left < right) {if(Str[left]! = Str[right]) {return false; }//ifleft++; right--; }//while return true; } };intMain () {solution S;stringStr"Aaba"); vector<vector<string> >result = S.partition (str);//Output for(inti =0; i < result.size (); ++i) { for(intj =0; J < Result[i].size (); ++j) {cout<<result[i][j]<<" "; }//for cout<<endl; }//for return 0; }
Run time
[Leetcode]131.palindrome Partitioning