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) {
string comb;
vector<string> res;
if (n<=0)
return res;
help(n,comb,res,0,0);
return res;
}
void help(int n, string & comb, vector<string> &res, int leftCount, int rightCount)
{
if (leftCount==n && rightCount ==n)
{
res.push_back(comb);
return;
}
if (leftCount<n)
{
comb.push_back('(');
help(n,comb,res,leftCount+1,rightCount);
comb.pop_back();
}
if (rightCount<leftCount)
{
comb.push_back(')');
help(n,comb,res,leftCount,rightCount+1);
comb.pop_back();
}
}
};
No comments:
Post a Comment