其他分享
首页 > 其他分享> > 22.括号生成——回溯

22.括号生成——回溯

作者:互联网

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> vec_str;
        string str;
        backtrack(vec_str, str, 0, 0, n);
        return vec_str;
    }
    void backtrack(vector<string>& vec_str, string& str, int left, int right, int n){
        if(str.size() == n * 2){
            vec_str.push_back(str);
            return;
        }
        if(left < n){
            str.push_back('(');
            backtrack(vec_str, str, left + 1, right, n);
            str.pop_back();
        }
        if(left > right){
            str.push_back(')');
            backtrack(vec_str, str, left, right + 1, n);
            str.pop_back();
        }
    }
};

Accepted
8/8 cases passed (4 ms)
Your runtime beats 70.99 % of cpp submissions
Your memory usage beats 66.59 % of cpp submissions (11.2 MB)

标签:right,22,backtrack,back,括号,vec,str,回溯,left
来源: https://blog.csdn.net/The_Dan/article/details/122018724