Approach
Depth-first search
For Palindromepartition2, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 36 lines of C++ from the credited upstream file palindromePartition2.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution {5 public: 6 vector<vector<string> > partition(string s) {7 const int n = s.size();8 vector<vector<bool> > p(n, vector<bool>(n, false));9 vector<string> path;10 vector<vector<string> > ans;11 buildPalindromeMap(s, p);12 dfs(s, p, 0, path, ans);13 return ans;14 }15 private:16 void buildPalindromeMap(const string &s, vector<vector<bool> > &p) {17 for (int i = s.size() - 1; i >= 0; --i)18 for (int j = i; j < s.size(); ++j)19 p[i][j] = s[i] == s[j] && ((j - i < 2) || p[i + 1][j - 1]); 20 }21 void dfs(const string &s, const vector<vector<bool> > &p, int start,22 vector<string> &path, vector<vector<string> > &ans) {23 if(start == s.size()) {24 ans.push_back(path);25 return; 26 }27 for(size_t i = start; i < s.size(); ++i) {28 if(p[start][i]) {29 path.push_back(s.substr(start, i - start + 1));30 dfs(s, p, i + 1, path, ans);31 path.pop_back();32 }33 }34 }35};36