leetcode22括号生成--回溯法
比较有意思的回溯题, 记录一下
class Solution {
vector<string> res {};
public:
vector<string> generateParenthesis(int n) {
string s;
// 0 -> number of open parenth
backtrack(0, 0, n, s);
return res;
}
void backtrack(int l, int r, int n, string &s) {
if (s.size() == n*2) {
res.push_back(s);
return;
}
if (l < n) {
s.push_back('(');
backtrack(l+1, r, n, s);
s.pop_back();
}
// 注意是if 不是else if, 这样能补充')'到相应数量
// ((( -> ((()))
// 回溯时
// 因为左括号回溯完后会进行接下来的步骤加入')'
// ((())) -> ((( -> (( -> (() -> (()())
// (()()) -> (()( -> ( -> () -> ()()()
if (r < l) {
s.push_back(')');
backtrack(l, r+1, n, s);
s.pop_back();
}
}
};