0022. 括号生成 #68
utterances-bot
started this conversation in
Comments
Replies: 3 comments
-
附上C++代码 |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
有没有机会在生成步骤就判断括号是否合理剪枝呀? |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
显式回溯 class Solution {
private:
vector<string> res;
string path;
int limit;
void backtrack(int open, int close) {
if (path.size() == 2 * limit) {
res.emplace_back(path);
return;
}
if (open < limit) {
path += '(';
backtrack(open + 1, close);
path.pop_back();
}
if (close < open) {
path += ')';
backtrack(open, close + 1);
path.pop_back();
}
return;
}
public:
vector<string> generateParenthesis(int n) {
res.clear();
path.clear();
this->limit = n;
backtrack(0, 0);
return res;
}
};隐式回溯 class Solution {
private:
vector<string> res;
int limit;
void backtrack(string cur, int open, int close) {
if (cur.size() == 2 * limit) {
res.emplace_back(cur);
return;
}
if (open < limit) {
backtrack(cur + '(', open + 1, close);
}
if (close < open) {
backtrack(cur + ')', open, close + 1);
}
return;
}
public:
vector<string> generateParenthesis(int n) {
res.clear();
this->limit = n;
backtrack("", 0, 0);
return res;
}
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
0022. 括号生成 | 算法通关手册
https://algo.itcharge.cn/solutions/0001-0099/generate-parentheses/
Beta Was this translation helpful? Give feedback.
All reactions