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