22. 括号生成
问题
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
分析
dfs,在每个位置选择'('或')'。另外,要满足括号有效,需要记录每个子问题左右括号的可用数量。显然,初始l_num == n>>1, r_num = 0,之后每选用一个'(',r_num+1. 也可以用栈记录右括号的可用,然而似乎没有必要,这样一个数字就够了。
代码
class Solution {
public:
int n_char;
vector<string> res;
void dfs(int x, int l_nums, int r_nums, string s_temp) {
if (x == n_char) {
if (l_nums == 0 && r_nums == 0) {
res.push_back(s_temp);
}
}
if (x > n_char) {return ;}
if (l_nums < 0 || r_nums < 0) {return ;}
// 选左
s_temp += '(';
dfs(x+1, l_nums-1, r_nums+1, s_temp);
// 选右
if (r_nums == 0) {return ;}
s_temp.pop_back();
s_temp += ')';
dfs(x+1, l_nums, r_nums-1, s_temp);
}
vector<string> generateParenthesis(int n) {
this->n_char = n*2;
string s = "";
dfs(0, n, 0, s);
return res;
}
};

浙公网安备 33010602011771号