leetcode22. 括号生成 medium
题目描述:
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
解题思路:
常规的dfs,string one的每一个位置各加一次左括号和右括号(用前缀和来判断能不能加右括号)
代码:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ret;
string one(2*n, 0);
dfs(ret, one, 0, 0, n, n);
return ret;
}
/*
* prefix_sum: 当前前缀和
* l_n: 剩余的 左括号数
* r_n: 剩余的 右括号数
*
*/
void dfs(vector<string> &ret, string &one, int cur_idx, int prefix_sum, int l_n, int r_n){
if (cur_idx == one.size()){
ret.push_back(one);
return;
}
if (l_n){
one[cur_idx] = '(';
dfs(ret, one, cur_idx+1, prefix_sum+1, l_n-1, r_n);
}
if (r_n && prefix_sum > 0){
one[cur_idx] = ')';
dfs(ret, one, cur_idx+1, prefix_sum-1, l_n, r_n-1);
}
}
};