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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
解法:
比较intuitive:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
generate(ans,"",n,0);
return ans;
}
void generate(vector<string>& ans,string str,int l,int r){
if(l==0&&r==0){
ans.emplace_back(str);
return;
}
if(l>0){
generate(ans,str+"(",l-1,r+1);
}
if(r>0){
generate(ans,str+")",l,r-1);
}
}
};
很久没有写递归的代码了,特此记录。