1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { vector<vector<string>> ans; public: vector<vector<string>> partition(string s) { vector<string> path; partitionImpl(s, 0, s.size(), path); return ans; } void partitionImpl(string &s, int start, int end, vector<string> &path){ if(end <= start){ return; } if(isPalindrome(s, start, end)){ path.push_back(s.substr(start, end - start)); ans.push_back(path); path.pop_back(); } for(int i = start + 1; i <= end; i++){ if(!isPalindrome(s, start, i)) continue; path.push_back(s.substr(start, i - start)); partitionImpl(s, i, end, path); path.pop_back(); } } bool isPalindrome(string &s, int start, int end){ if(end - start <= 1) return true; for(int i = 0; i < (end - start) / 2; i++){ if(s[start + i] != s[end - i - 1]) return false; } return true; } };
|