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:
"((()))", "(()())", "(())()", "()(())", "()()()"
void generateParenthesisRecurse(string &s, int x, int y, int n, vector<string> &v)
{
if(y>x)return;
if (x+y == n)
{
if(x==y)
v.push_back(s);
return;
}
s[x+y] = '(';
generateParenthesisRecurse(s, x+1, y, n, v);
s[x+y] = ')';
generateParenthesisRecurse(s, x, y+1, n, v);
}
vector<string> generateParenthesis(int n) {
vector<string> V;
string s;
for (int i = 0; i<n*2; i++)s+='(';
generateParenthesisRecurse(s, 0, 0, n*2, V);
return V;
}
No comments:
Post a Comment