Problem solution · C++

Palindromepartition2

Palindromepartition2: a C++ solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Depth-first search
Source
Kamyu LeetCode Solutions
Length
36 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Palindromepartition2, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. 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.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codePalindromepartition2 · C++C++
Use this to learn the idea, then write your own version.
// Time Complexity: O(2^n)// Space Complexity: O(n^2) class Solution {    public:              vector<vector<string> > partition(string s) {            const int n = s.size();            vector<vector<bool> > p(n, vector<bool>(n, false));            vector<string> path;            vector<vector<string> > ans;            buildPalindromeMap(s, p);            dfs(s, p, 0, path, ans);            return ans;        }    private:        void buildPalindromeMap(const string &s, vector<vector<bool> > &p) {            for (int i = s.size() - 1; i >= 0; --i)                for (int j = i; j < s.size(); ++j)                    p[i][j] = s[i] == s[j] && ((j - i < 2) || p[i + 1][j - 1]);           }        void dfs(const string &s, const vector<vector<bool> > &p, int start,                vector<string> &path, vector<vector<string> > &ans) {            if(start == s.size()) {                ans.push_back(path);                return;                    }            for(size_t i = start; i < s.size(); ++i) {                if(p[start][i]) {                    path.push_back(s.substr(start, i - start + 1));                    dfs(s, p, i + 1, path, ans);                    path.pop_back();                }            }        }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗