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:
void foo(int n, vector<string> &retVector, string &curString, int leftNum, int rightNum)
{
if (leftNum == n && rightNum == n)
{
retVector.push_back(curString);
return;
}
if (leftNum < n)
{
curString.push_back('(');
foo(n, retVector, curString, leftNum+1, rightNum);
curString.pop_back();
}
if (rightNum < leftNum)
{
curString.push_back(')');
foo(n, retVector, curString, leftNum, rightNum+1);
curString.pop_back();
}
}
vector<string> generateParenthesis(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> retVector;
string curString;
if (n == 0)
{
return retVector;
}
int leftNum = 0;
int rightNum = 0;
foo(n, retVector, curString, leftNum, rightNum);
return retVector;
}
};