当前位置:网站首页>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();
}
}
};
边栏推荐
- [rust daily] 2022-04-19 performance evaluation of rust asynchronous framework
- Vins Theory and Code detail 4 - Initialization
- 4. Meet panuon again UI. Title bar of silver form
- 虚拟机ping不通的几种原因及解决办法
- 如何構建以客戶為中心的產品藍圖:來自首席技術官的建議
- 智能电网终极Buff | 广和通模组贯穿“发、输、变、配、用”全环节
- 2022第十四届南京国际人工智能产品展会
- Tensorflow actual combat Google deep learning framework second edition learning summary tensorflow introduction
- Golang beep package playback MP3 cannot get the total length streamer Len() is 0, but other formats can
- 云图说|每个成功的业务系统都离不开APIG的保驾护航
猜你喜欢

虚拟机ping不通的几种原因及解决办法

How to build a customer-centric product blueprint: suggestions from the chief technology officer

港大、英伟达 | Factuality Enhanced Language Models for Open-Ended Text Generation(用于开放式文本生成的事实性增强语言模型)

ORB_ Slam2 visual inertial tight coupling positioning technology route and code explanation 3 - tight coupling optimization model

数据库创建触发器的问题

Day10/11 递归 / 回溯

Golang beep package playback MP3 cannot get the total length streamer Len() is 0, but other formats can

Fast detection of short text repetition rate

Common QR decomposition, SVD decomposition and other matrix decomposition methods of visual slam to solve full rank and deficient rank least squares problems (analysis and summary of the most complete

Detailed explanation of binary search
随机推荐
Yuntu says that every successful business system cannot be separated from apig
ORB_ Slam2 visual inertial tight coupling positioning technology route and code explanation 2 - IMU initialization
json.load(s)与json.dump(s)
[reward publicity] [content co creation] issue 16 may Xu sublimation, create a good time! You can also win a gift package of up to 500 yuan if you sign a contract with Huawei cloud Xiaobian!
CVPR 2022 oral | SCI: fast, flexible and robust low light image enhancement
Vins theory and code explanation 4 - initialization
MITM(中间人攻击)
4. Meet panuon again UI. Title bar of silver form
2022 the 14th Nanjing International artificial intelligence product exhibition
Tensorflow actual combat Google deep learning framework second edition learning summary tensorflow introduction
点击解锁广和通5G模组“关键词”
How the autorunner automated test tool creates a project -alltesting | Zezhong cloud test
数据库创建触发器的问题
农产品期货如何开户?有没有什么资金条件?
点投影到平面上的方法总结
RSA a little bit of thought
Google Earth Engine(GEE)——基于s2影像的实时全球10米土地利用/土地覆盖(LULC)数据集
2022南京国际智慧工地装备展览会
ORB_SLAM2视觉惯性紧耦合定位技术路线与代码详解1——IMU流型预积分
数字化管理中台+低代码,JNPF开启企业数字化转型的新引擎