生成括号(递归方法)
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
C++版本。
vector<string> s;
run(s,"",n,0);
return s;
}
//l表示还差几个(,r表示还差几个) 来匹配
void run(vector<string> &s,string str,int l,int r){
if(l==0&&r==0){
s.push_back(str);
return ;
}
if(l>0){
run(s,str+"(",l-1,r+1);
}
if(r>0){
run(s,str+")",l,r-1);
}
}
java代码博客。