Simple non-recursive C++


  • 0
    S
    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<string> res(1, "(");
            vector<int> left(1, 1);
            int l=2*n;
            for(int i=1; i<l; i++)
            {
                for(int j=res.size()-1; j>=0; j--)
                {
                    if(left[j]>0)
                    {
                        if(left[j]<l-i)
                        {
                            res.emplace_back(res[j]+"(");
                            left.push_back(left[j]+1);
                        }
                        res[j]+=")";
                        left[j]--;
                    }
                    else
                    {
                        res[j]+="(";
                        left[j]++;
                    }
                }
            }
            return res;
        }
    };
    

Log in to reply
 

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