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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
Subscribe to see which companies asked this question
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
string s;
helper(res, s, n, n);
return res;
}
void helper(vector<string> &res, string &s, int left, int right){
if(left == 0 && right == 0){
res.push_back(s);
return;
}
if(left > 0) { s.push_back('('); helper(res, s, left - 1, right); s.pop_back();
}
if(left < right) {s.push_back(')'); helper(res, s, left, right - 1);s.pop_back();}
}
};