https://leetcode-cn.com/problems/generate-parentheses/
DFS回溯剪枝
剪枝:
每放一个左括号,才可以放一个右括号,即右括号不能先于左括号放置,亦即l >= r:左括号的数量大于或等于,右括号的数量才有可能符合解的条件,继续向下一层递归。(当然左右括号的数量都不能超过n)。
图片来源https://leetcode-cn.com/problems/generate-parentheses/solution/hui-su-suan-fa-by-liweiwei1419/
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
int l = 0, r = 0; //l: 左括号数,r: 右括号数
dfs(res, "", n, l, r);
return res;
}
private:
void dfs(vector<string>& res, const string &path, int n, int l, int r) {
if (r > l || l > n || r > n) return; //每放一个左括号,才可以放一个右括号
if (l == r && l == n) { //即右括号不能先于左括号放置
res.push_back(path); //亦即l >= r;左括号的数量大于或等于
return; //右括号的数量才有可能符合解的条件,继续向下一层递归
}
dfs(res, path + '(', n, l + 1, r);
dfs(res, path + ')', n, l, r + 1);
}
};