My 12ms C++ solution using DFS


  • 0
    H
    class Solution {
    public:
    bool is_palindrome(const string s,int low,int up)
    {
        while(low < up && s[low] == s[--up]) low++;
        return low >= up;
    }
    void dfs(const string s,vector<vector<string>> & ret,vector<string> & vect)
    {
        if(s.empty())
            ret.push_back(vect);
        for(int i = 1 ; i <= s.length(); i++)
            if(is_palindrome(s,0,i))
            {
                vect.push_back(s.substr(0,i));
                dfs(s.substr(i),ret,vect);
                vect.pop_back();
            }
    }
    vector<vector<string>> partition(string s) {
        vector<vector<string>> ret;
        vector<string> vect;
        dfs(s,ret,vect);
        return ret;
    }
    };

Log in to reply
 

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