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 {
private:
void generateParenthesisHelper(int leftNum, int rightNum, int totalNum, int curIdx, vector<char> &curString, vector<string> &retVtr) {
if (leftNum == totalNum && rightNum == totalNum)
{
string str(curString.begin(), curString.end());
retVtr.push_back(str);
return;
}
if (leftNum < totalNum)
{
curString[curIdx] = '(';
generateParenthesisHelper(leftNum+1, rightNum, totalNum, curIdx+1, curString, retVtr);
}
if (rightNum < leftNum)
{
curString[curIdx] = ')';
generateParenthesisHelper(leftNum, rightNum+1, totalNum, curIdx+1, curString, retVtr);
}
}
public:
vector<string> generateParenthesis(int n) {
vector<string> retVtr;
vector<char> curString(n*2,0);
generateParenthesisHelper(0, 0, n, 0, curString, retVtr);
return retVtr;
}
};