Share my C++ backtracking solution


  • 0
    class Solution {
    private:
        bool judge(string s, int start, int end)
        {
            while(start <= end)
            {
                if(s[start] != s[end])
                {
                    return false;
                }
                start++, end--;
            }
            return true;
        }
    public:
        vector<vector<string>> partition(string s) {
            vector<vector<string>> result;
            vector<string> p;
            backtracking(s, result, p, 0);
            return result;
        }
    
        void backtracking(string &s, vector<vector<string>> &result, vector<string> p, unsigned int start)
        {
            if(start == s.length())
            {
                result.push_back(p);
                return;
            }
    
            for(unsigned int i = start; i < s.length(); i++)
            {
                if(judge(s, start, i))
                {
                    p.push_back(s.substr(start, i - start + 1));
                    backtracking(s, result, p, i + 1);
                    p.pop_back();
                }
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.