给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。例如,给出 n = 3,生成结果为:[ "((()))", "(()())", "(())()", "()(())", "()()()"]算法:暴搜(dfs)。我们搜索出所有的结果并进行保存即可。
class Solution {
public:
vector<
string>
res;
void dfs(
int l,
int r,
int n,
string cur){
if(l==n&&r==
n){
res.push_back(cur);
return ;
}
if(l<
n)
dfs(l+
1,r,n,cur+
"(");
if(r<
l)
dfs(l,r+
1,n,cur+
")");
}
vector<
string> generateParenthesis(
int n) {
if(n==
0)
return {
""};
dfs(0,
0,n,
"");
return res;
}
};
转载于:https://www.cnblogs.com/programyang/p/11171973.html