题目:
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
代码:
class Solution {
public:
vector<string> generateParenthesis(int n) {
int left = n;
int right = n;
vector<string> res;
c(res, string(""), left, right);
return res;
}
void c(vector<string>& res, string s, int left, int right){
if(left == 0 && right == 0) res.push_back(s);
if(left > 0) c(res, s+'(', left-1,right);
if(right > left) c(res, s+')', left, right-1);
}
};