给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
此题要注意添加)的数目比(的数目小且还有剩余使才能添加。。。
当全部添加完毕时,return。
代码如下:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ve;
if(n==0)
return ve;
dfs ("",n,n,ve);
return ve;
}
void dfs (string s,int x,int y,vector<string>&ve)
{
if(x==0&&y==0)
{
ve.push_back(s);
return;
}
if(x)
dfs (s+'(',x-1,y,ve);
if(y&&y>x)
dfs (s+')',x,y-1,ve);
}
};