Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
括号问题,要算输出个数的话是卡特兰数,要输出所有情况的话是递归。
这道题关键在递归参数的选择上,仔细想来,一定得是左右括号的数量,以及括号字符串的中间结果,
代码如下:
void f(int n, int l,int r,string s){
if(l==n&&r==n){
result.push_back(s);
return;
}
if(l>r){
f(n,l,r+1,s+")");
}
if(l<n)
f(n,l+1,r,s+"(");
}
vector<string> generateParenthesis(int n){
f(n,0,0,"");
return result;
}