Given a stringS, PartitionSSuch that every substring of the partition is a palindrome.
Return all possible palindrome partitioningS.
For example, givenS="aab"
, Return
[["AA", "B"], ["A", "A", "B"]
Note the following example:
Input: |
"Fff" |
Expected: |
[["F", "F", "F"], ["F", "FF"], ["FF", "F"], ["fff"] |
class Solution {public: vector<vector<string>> partition(string s) { vector<vector<string>> res; if(s.size()<1) return res; vector<string> partition; addPalindrome(s,0,partition,res); return res; }private: void addPalindrome(string s,int start,vector<string> &partition,vector<vector<string> >&res){ if(start == s.size()){ res.push_back(partition); return; } for(int i = start+1;i<=s.size();i++){ string str = s.substr(start,i-start); if(isPalindrome(str)){ partition.push_back(str); addPalindrome(s,i,partition,res); partition.pop_back(); }//end if }//end for } bool isPalindrome(string str){ int left = 0; int right = str.size()-1; while(left<right){ if(str[left]!=str[right]) return false; left++; right--; }//end while return true; }};
Method: DFS!