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) {
vector<string> res;
if(n==0)
return res;
string s;
dfs(res,s,n,n);
return res;
}
void dfs(vector<string>& res, string& s, int left, int right)
{
if(left>right)
return;
if(left==0&&right==0)
{
res.push_back(s);
return;
}
if(left>0)
{
s.push_back('(');
dfs(res,s,left-1,right);
s.pop_back();
}
if(right>0)
{
s.push_back(')');
dfs(res,s,left,right-1);
s.pop_back();
}
}
};