思路:
又一个dfs问题, 回溯法很容易能够解决, 要注意只有剩下的右括号比左括号多的时候才继续进行下去
void dfs(vector<string>& res,
string& candidate,
int nLeft,
int nRight) {
// 剪枝, 左括号要剩的多了肯定不是合法字符串
if (nLeft > nRight) return;
if (! nRight)
res.push_back(candidate);
else {
if (nLeft) {
candidate += '(';
dfs(res, candidate, nLeft - 1, nRight);
candidate.pop_back();
}
candidate += ')';
dfs(res, candidate, nLeft, nRight - 1);
candidate.pop_back();
}
}
vector<string> generateParenthesis(int n) {
vector<vector<string>> res;
string candidate = "(";
dfs(res, candidate, n - 1, n);
return res;
}