给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
class Solution {
public:
vector<string> v;
int N;
void dfs(int left,int right,string s)
{
if(right > left)
return;
if(left > N)
return;
if(left == right && left == N){
v.push_back(s);
return;
}
dfs(left + 1,right, s + "(");
dfs(left,right + 1, s + ")");
}
vector<string> generateParenthesis(int n) {
N = n;
if(!n)
return {};
dfs(0,0,"");
return v;
}
};