C++ 0ms solution


  • 0
    X
    class Solution {
    public:
        // l is left parentheses used, r is right parentheses used
        // cur is initialized with ')'
        void search(int l, int r, int n, string& cur, vector<string> &ret) {
            if (l == n) {
                ret.push_back(cur);
                return;
            }  
            if (r < l) search(l, r+1, n, cur, ret);
            
            cur[l+r] = '(';
            search(l+1, r, n, cur, ret);
            cur[l+r] = ')';
        }
        
        vector<string> generateParenthesis(int n) {
            string cur;
            vector<string> ret;
            
            cur.resize(2*n, ')');
            ret.reserve(2 * n);
            search(0, 0, n, cur, ret);
            
            return ret;
        }
    };

Log in to reply
 

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