力扣第22题 括号生成
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;
}
};