Note:判断是否合法
(1)任意前缀中,“(” 数量 >= “)”数量
(2)左右括号数量相等
Note:可添加括号的情况
左括号:只要l_cnt < n 就可以添加左括号
有括号:r_cnt < n 并且 l_cnt 严格大于 r_cnt
代码如下:
class Solution {
public:
vector<string> ans;
vector<string> generateParenthesis(int n) {
dfs(n, 0, 0, "");
return ans;
}
void dfs(int n, int lc, int rc, string seq){
if(lc == n && rc == n) ans.push_back(seq);
else{
if(lc < n) dfs(n, lc + 1, rc, seq + "(");
if(rc < n && lc > rc) dfs(n, lc, rc + 1, seq + ")");
}
}
};