力扣第22题 括号生成
![](https://img2020.cnblogs.com/blog/384305/202004/384305-20200409225952189-1516861457.png)
![](https://img2020.cnblogs.com/blog/384305/202004/384305-20200409230002518-1995482487.png)
class Solution {
public:
// 括号生成
void backtrack(vector<string> &res, string& cur, int left, int right, const int& n)
{
if (left + right == 2 * n)
{
res.push_back(cur);
return;
}
if (left < n)
{
cur.push_back('(');
backtrack(res, cur, left + 1, right, n);
cur.pop_back();
}
if (right < left && right < n)
{
cur.push_back(')');
backtrack(res, cur, left, right + 1, n);
cur.pop_back();
}
}
vector<string> generateParenthesis(int n)
{
vector<string> result;
string s = "";
backtrack(result, s, 0, 0, n);
return result;
}
};