Share my c++ AC code ~ using recursion, easy to understand


  • 0
    O
    vector<string> generateParenthesis(int n) {
        vector <string> ret;
        if (n == 1)    {
            ret.push_back ("()");    return ret;
        }
        vector <string> t = generateParenthesis (n - 1);
        for (int i = 0; i < t.size (); i ++) {
            string a;
            int k = 0;
            int cnt = 0;
            for (;k <= t [i].length (); k ++) {
                if (cnt == 0) {
                    string x = t [i].substr (0, k);
                    string y = t [i].substr (k, t[i].size());
                    a = "(" + x + ")" + y;
                    if (a.length () == 2 * n && find (ret.begin (), ret.end (), a) == ret.end ())
                        ret.push_back (a);
                }
                if (t [i][k] == '(')
                    cnt ++;
                else
                    cnt --;
            }
    
        }
        return ret;
    }

Log in to reply
 

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