LeetCode OJ:Palindrome Partitioning(回文排列)
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"] ]
典型的dfs,代码如下:
1 class Solution { 2 public: 3 vector<vector<string>> partition(string s) { 4 vector<string> path; 5 dfs(s, path); 6 return ret; 7 } 8 9 void dfs(string s, vector<string> & path) 10 { 11 if(s.size() < 1) 12 ret.push_back(path); 13 for(int i = 0; i < s.size(); ++i){ 14 int start = 0; 15 int end = i; 16 while(start < end){ 17 if(s[start] == s[end]) 18 start++, end--; 19 else 20 break; 21 } 22 if(start >= end){ 23 path.push_back(s.substr(0,i+1)); 24 dfs(s.substr(i+1), path); 25 path.pop_back(); 26 } 27 } 28 } 29 30 private: 31 vector<vector<string>> ret; 32 33 };