Problem:
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"] ]
Analysis:
At first glance, it seems very hard. But it's a DFS problem. What is the possible choice? A substring is a possible if it's a palindrom. Then if the substring is valid, then we can recursivly call the solve on the remaining substring to continue generate palindrom until the current position is greater or equal than the total string's length.
Code:
1 class Solution { 2 public: 3 vector<vector<string> > res; 4 vector<string> tmp; 5 6 vector<vector<string>> partition(string s) { 7 // Start typing your C/C++ solution below 8 // DO NOT write int main() function 9 res.clear(); 10 tmp.clear(); 11 12 if (s == "") return res; 13 14 solve(s, 0); 15 16 return res; 17 } 18 19 private: 20 bool solve(string s, int p) { 21 if (p >= s.length()) { 22 res.push_back(tmp); 23 return true; 24 } 25 26 int lmt = s.length() - p; 27 for (int l=1; l <= lmt; l++) { 28 string st = s.substr(p, l); 29 30 if (isPalindrom(st)) { 31 tmp.push_back(st); 32 solve(s, p+l); 33 tmp.pop_back(); 34 } 35 } 36 37 return false; 38 } 39 40 bool isPalindrom(string s) { 41 int i=0, j=s.length()-1; 42 43 while (i < j) { 44 if(s[i++] != s[j--]) 45 return false; 46 } 47 48 return true; 49 } 50 };