当前位置:网站首页>22. Generate Parentheses
22. Generate Parentheses
2022-06-10 15:24:00 【soO_007】
题目:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1 Output: ["()"]
Constraints:
1 <= n <= 8
思路1:
题意大致是给定一个整数n,返回所有有效的的拥有n对括号的string。首先成立的string一定是2 * n长度,即n个左括号和n个右括号构成,另外再证明有效性即可。因为数据量只到8,所以暴力搜索是可以过的。回溯的base case是string长度到达2 * n并且能够被证明有效性。
代码1:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<int> rest = { n, n };
backtracking(s, 0, rest, n);
return res;
}
private:
vector<string> res;
string s;
bool check(string& s) {
stack<char> st;
for (auto c : s) {
if (c == ')') {
if (st.size() && st.top() == '(')
st.pop();
else
return false;
}
else
st.push(c);
}
return st.empty();
}
void backtracking(string &s, int cur, vector<int>& rest, int n) {
if (s.size() == 2 * n) {
if (check(s))
res.push_back(s);
return;
}
for (int i = cur; i < 2 * n; i++) {
if (rest[0] > 0) {
s.push_back('(');
rest[0]--;
backtracking(s, i + 1, rest, n);
s.pop_back();
rest[0]++;
}
if (rest[1] > 0) {
s.push_back(')');
rest[1]--;
backtracking(s, i + 1, rest, n);
s.pop_back();
rest[1]++;
}
}
}
};
思路2:
我们也可以在保证有效性的情况下添加括号,分为两种条件1)如果左括号还能添加,即当前string中左括号的数量小于n,那么可以无脑添加,不会影响有效性;2)如果string中右括号比左括号少,则也可以添加右括号。这样在base case跳出的时候就不用额外判断是否有效了,直接把当前string添加到集合即可。
代码2:
class Solution {
public:
vector<string> generateParenthesis(int n) {
backtracking(s, 0, 0, n);
return res;
}
private:
vector<string> res;
string s;
void backtracking(string &s, int left, int right, int n) {
if (s.size() == 2 * n) {
res.push_back(s);
return;
}
if (left < n) {
s.push_back('(');
backtracking(s, left + 1, right, n);
s.pop_back();
}
if (right < left) {
s.push_back(')');
backtracking(s, left, right + 1, n);
s.pop_back();
}
}
};
边栏推荐
- 广和通高算力智能模组为万亿级市场5G C-V2X注智
- [high code file format API] Shanghai daoning provides you with the file format API set Aspose, which can create, convert and operate more than 100 file formats in just a few lines of code
- Google Earth Engine(GEE)——基于s2影像的实时全球10米土地利用/土地覆盖(LULC)数据集
- QT interface nested movement based on qscrollarea
- Sanzi chess (implemented in C language)
- 2022 Nanjing International Smart site equipment exhibition
- 4、再遇Panuon.UI.Silver之窗体标题栏
- How to build a customer-centric product blueprint: suggestions from the chief technology officer
- Wechat applet color gradient
- Detailed explanation of binary search
猜你喜欢

Day10/11 递归 / 回溯

Explain the opencv function filter2d() in detail and remind you that the operation it does is not convolution but correlation operation

AutoRunner自动化测试工具如何创建项目-Alltesting|泽众云测试
![[high code file format API] Shanghai daoning provides you with the file format API set Aspose, which can create, convert and operate more than 100 file formats in just a few lines of code](/img/43/086da4950da4c6423d5fc46e46b24f.png)
[high code file format API] Shanghai daoning provides you with the file format API set Aspose, which can create, convert and operate more than 100 file formats in just a few lines of code

AEC of the three swordsmen in audio and video processing: the cause of echo generation and the principle of echo cancellation

企业如何提升文档管理水平

2022 Nanjing International Smart site equipment exhibition

Problems with database creation triggers

Day10/11 recursion / backtracking

信息论与编码2 期末复习-BCH码
随机推荐
We media video Hot Ideas sharing
json.load(s)与json.dump(s)
Applet to realize global data sharing
How to solve the problem that SVN cannot open the URL address
How to build a customer-centric product blueprint: suggestions from the chief technology officer
OpenTelemetry Metrics发布候选版本
Sanzi chess (implemented in C language)
Net core Tianma XingKong series - Interface Implementation for dependency injection and mutual conversion of database tables and C entity classes
详解OpenCV的函数filter2D(),并提醒大家它做的运算并不是卷积运算而是相关运算
How to improve document management
Jiabo gp2120tu label printer installation and use tutorial (PC)
How to realize ERP extranet connection?
3. Encounter the form of handycontrol again
Docket command
2022 Nanjing International Smart site equipment exhibition
ORB_SLAM2视觉惯性紧耦合定位技术路线与代码详解3——紧耦合优化模型
Self recommendation - in depth understanding of the rust Standard Library Kernel
【Rust日报】2022-04-19 Rust异步框架的性能评估
洞察的力量
MITM(中间人攻击)