力扣第22题 括号生成

力扣第22题 括号生成

class Solution {
public:
// 括号生成
    void backtrack(vector<string> &res, string& cur, int left, int right, const int& n)
    {
        if (left + right == 2 * n)
        {
            res.push_back(cur);
            return;
        }
        if (left < n)
        {
            cur.push_back('(');
            backtrack(res, cur, left + 1, right, n);
            cur.pop_back();
        }
        if (right < left && right < n)
        {
            cur.push_back(')');
            backtrack(res, cur, left, right + 1, n);
            cur.pop_back();
        }
    }

    vector<string> generateParenthesis(int n) 
    {
        vector<string> result;
        string s = "";
        backtrack(result, s, 0, 0, n);
        return result;
    }

};

posted on 2020-04-10 22:36  woodjay  阅读(196)  评论(0编辑  收藏  举报

导航