深度优先遍历
class Solution {
public:
vector<string> res;
void dfs(string tmp, int left, int right, int n)
{
if (left == n && right == n) //当左右括号数量都等于n时为一种有效组合
{
res.push_back(tmp);
return;
}
if (left < right) return; //剪枝,左括号数量小于右括号时是不合法的,直接返回
if (left < n) dfs(tmp + '(', left + 1, right, n); //继续添加左括号
if (right < n) dfs(tmp + ')', left, right + 1, n); //继续添加右括号
}
vector<string> generateParenthesis(int n) {
dfs("", 0, 0, n);
return res;
}
};