牛客题霸 [括号生成] C++题解/答案

牛客题霸 [括号生成] C++题解/答案

题意:

给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。
例如,给出n=3,解集为:
“((()))”, “(()())”, “(())()”, “()()()”, “()(())”,

题解:

回溯法
当左括号少于n时就添加做括号
右括号数量小于左括号数量时继续添加右括号

代码:

class Solution {
public:
    /**
     * 
     * @param n int整型 
     * @return string字符串vector
     */
   void backtrack(string str, int open, int close, int n, vector<string>& res) {
        if(str.size() == (n << 1)) {
            res.push_back(str);
            return;
        }
        if(open < n) {
            backtrack(str + "(", open + 1, close, n, res);
        }
        if(close < open) {
            backtrack(str + ")", open, close + 1, n, res);
        }
    }
     
    vector<string> generateParenthesis(int n) {
        // write code here
        if(n < 1) return {};
        vector<string> res;
        backtrack("", 0, 0, n, res);
        return res;
    }
};
posted @ 2020-11-19 21:50  回归梦想  阅读(210)  评论(0编辑  收藏  举报