Sharing my 0ms C++ solution using recursion


  • 1
    T
    class Solution {
    private:
        void generateParenthesisHelper(vector<string>& result, int n, int nleft, int nright, string s)
        {
            if(nleft==n && nright==n)
            {
                result.push_back(s);
                return;
            }
            else if(nleft == n)
            {
                int i;
                string S = s;
                for(i=0; i<n-nright; i++)
                    S = S + ')';
                result.push_back(S);
                return;
            }
            else if(nleft==nright)
            {
                generateParenthesisHelper(result, n, nleft+1, nright, s+'(');
            }
            else
            {
                generateParenthesisHelper(result, n, nleft+1, nright, s+'(');
                generateParenthesisHelper(result, n, nleft, nright+1, s+')');
            }
        }
        
    public:
        vector<string> generateParenthesis(int n) {
            vector<string> result;
            int nleft=0;
            int nright=0;
            string s;
            generateParenthesisHelper(result, n, nleft, nright, s);
            return result;
        }
    };

Log in to reply
 

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