Difficulty: Medium
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
具体的方法是通过两个int le 和ri 来记录'('和‘)'的剩余个数,递归赋值,列遍所有可能,算法非常巧妙。
void gen(int le, int ri, string s, vector<string>& ans){
if(le==0&&ri==0)
ans.push_back(s);
if(le>0){
gen(le-1,ri,s+'(',ans);
}
if(ri>le&&ri>0){
gen(le,ri-1,s+')',ans);
}
}
vector<string> generateParenthesis(int n) {
vector<string> ans;
string s;
gen(n,n,s,ans);
return ans;
}