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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
C++
vector<string> generateParenthesis(int n) {
vector<string> res;
string s = "";
DFS(n,n,s,res);
return res;
}
void DFS(int left,int right,string s,vector<string>& res)
{
if(left > right)
return;
if(left == 0&&right == 0)
res.push_back(s);
else
{
if(left > 0)DFS(left - 1,right,s + "(",res);
if(right > 0)DFS(left,right - 1,s+")",res);
}
}