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;
string str = "";
DFS(res, str, n, n);
return res;
}
void DFS(vector<string>& res, string str, int left, int right)
{
if(left == 0 && right == 0)
{
res.push_back(str);
return ;
}
if(left > 0)
DFS(res, str + "(", left - 1, right);
if(right > 0 && left < right)
DFS(res, str + ")", left, right - 1);
}
};