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

数据范围:$1≤n≤8$

示例1

输入:

1

返回值:

["()"]

示例2
输入:

2

返回值:

["(())","()()"]

题解

class Solution {
public:
    /**
     * 
     * @param n int整型 
     * @return string字符串vector
     */
    vector<string> res;
    vector<string> generateParenthesis(int n) {
        backtracking("", 0, 0, n);
        return res;
    }
    
    void backtracking(string s, int st, int ed, int n) {
        if(s.size() == n * 2) {
            res.push_back(s);
            return;
        }
        if(st < n) backtracking(s + "(", st+1, ed, n);
        if(ed < st) backtracking(s + ")", st, ed+1, n);
    }        
};
Last modification:March 30, 2022
如果觉得我的文章对你有用,请随意赞赏