[LeetCode] 22. Generate Parentheses 生成括号
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
在 LeetCode 中有关括号的题共有七道,除了这一道的另外六道是 Score of Parentheses,Valid Parenthesis String, Remove Invalid Parentheses,Different Ways to Add Parentheses,Valid Parentheses 和 Longest Valid Parentheses。这道题给定一个数字n,让生成共有n个括号的所有正确的形式,对于这种列出所有结果的题首先还是考虑用递归 Recursion 来解,由于字符串只有左括号和右括号两种字符,而且最终结果必定是左括号3个,右括号3个,所以这里定义两个变量 left 和 right 分别表示剩余左右括号的个数,如果在某次递归时,左括号的个数大于右括号的个数,说明此时生成的字符串中右括号的个数大于左括号的个数,即会出现 ')(' 这样的非法串,所以这种情况直接返回,不继续处理。如果 left 和 right 都为0,则说明此时生成的字符串已有3个左括号和3个右括号,且字符串合法,则存入结果中后返回。如果以上两种情况都不满足,若此时 left 大于0,则调用递归函数,注意参数的更新,若 right 大于0,则调用递归函数,同样要更新参数,参见代码如下:
C++ 解法一:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
generateParenthesisDFS(n, n, "", res);
return res;
}
void generateParenthesisDFS(int left, int right, string out, vector<string> &res) {
if (left > right) return;
if (left == && right == ) res.push_back(out);
else {
if (left > ) generateParenthesisDFS(left - , right, out + '(', res);
if (right > ) generateParenthesisDFS(left, right - , out + ')', res);
}
}
};
Java 解法一:
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
helper(n, n, "", res);
return res;
}
void helper(int left, int right, String out, List<String> res) {
if (left < 0 || right < 0 || left > right) return;
if (left == 0 && right == 0) {
res.add(out);
return;
}
helper(left - 1, right, out + "(", res);
helper(left, right - 1, out + ")", res);
}
}
再来看那一种方法,这种方法是 CareerCup 书上给的方法,感觉也是满巧妙的一种方法,这种方法的思想是找左括号,每找到一个左括号,就在其后面加一个完整的括号,最后再在开头加一个 (),就形成了所有的情况,需要注意的是,有时候会出现重复的情况,所以用set数据结构,好处是如果遇到重复项,不会加入到结果中,最后我们再把set转为vector即可,参见代码如下::
n=1: ()
n=2: (()) ()()
n=3: (()()) ((())) ()(()) (())() ()()()
C++ 解法二:
class Solution {
public:
vector<string> generateParenthesis(int n) {
unordered_set<string> st;
if (n == ) st.insert("");
else {
vector<string> pre = generateParenthesis(n - );
for (auto a : pre) {
for (int i = ; i < a.size(); ++i) {
if (a[i] == '(') {
a.insert(a.begin() + i + , '(');
a.insert(a.begin() + i + , ')');
st.insert(a);
a.erase(a.begin() + i + , a.begin() + i + );
}
}
st.insert("()" + a);
}
}
return vector<string>(st.begin(), st.end());
}
};
Java 解法二:
public class Solution {
public List<String> generateParenthesis(int n) {
Set<String> res = new HashSet<String>();
if (n == 0) {
res.add("");
} else {
List<String> pre = generateParenthesis(n - 1);
for (String str : pre) {
for (int i = 0; i < str.length(); ++i) {
if (str.charAt(i) == '(') {
str = str.substring(0, i + 1) + "()" + str.substring(i + 1, str.length());
res.add(str);
str = str.substring(0, i + 1) + str.substring(i + 3, str.length());
}
}
res.add("()" + str);
}
}
return new ArrayList(res);
}
}
Github 同步地址:
https://github.com/grandyang/leetcode/issues/22
类似题目:
Different Ways to Add Parentheses
参考资料:
https://leetcode.com/problems/generate-parentheses/
https://leetcode.com/problems/generate-parentheses/discuss/10127/An-iterative-method.
https://leetcode.com/problems/generate-parentheses/discuss/10337/My-accepted-JAVA-solution
https://leetcode.com/problems/generate-parentheses/discuss/10105/Concise-recursive-C%2B%2B-solution
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] 22. Generate Parentheses 生成括号的更多相关文章
- [leetcode]22. Generate Parentheses生成括号
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- [CareerCup] 9.6 Generate Parentheses 生成括号
9.6 Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-p ...
- 22.Generate Parentheses[M]括号生成
题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...
- generate parentheses(生成括号)
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- [LintCode] Generate Parentheses 生成括号
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- [LeetCode]22. Generate Parentheses括号生成
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- [LeetCode] Generate Parentheses 生成括号
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- 22. Generate Parentheses生成指定个括号
生成指定个数的括号,这些括号可以相互包括,但是一对括号的格式不能乱(就是配对的一个括号的左括号要在左边,右括号要在右边) 思维就是从头递归的添加,弄清楚什么时候要添加左括号,什么时候添加右括号 有点像 ...
- LeetCode 22 Generate Parentheses(找到所有匹配的括号组合)
题目链接 : https://leetcode.com/problems/generate-parentheses/?tab=Description 给一个整数n,找到所有合法的 () pairs ...
随机推荐
- learning rate warmup实现
def noam_scheme(global_step, num_warmup_steps, num_train_steps, init_lr, warmup=True): ""& ...
- 【转】Visual Studio 2008 可扩展性开发(二):Macro和Add-In初探
前言 在VS概览中,我们简单回顾了一下VS的历史.本文将通过两个简单的例子来说明Macro和Add-In的开发.通过Macro我们把VS中的一些重复操作录制下来,之后可以多次运行,节省时间并保持好的心 ...
- WinForm 窗体间传递数据
前言 做项目的时候,winfrom因为没有B/S的缓存机制,窗体间传递数据没有B/S页面传递数据那么方便,今天我们就说下winfrom中窗体传值的几种方式. 共有字段传递 共有字段传递实现起来很方便, ...
- NLP第二课(搜索)
最近压力太大了,持续性修改0注释的代码,变量为阿拉伯数字的代码,压力山大,摆正心态,没有那些bug,还需要我们来做些什么呢?如果一个特别出色的项目,也体现不出来你个人的出色.几句牢骚,我们今天来继续说 ...
- VM1059 bootstrap-table.min.js:7 Uncaught TypeError: Cannot read property 'classes' of undefined
参考链接:https://blog.csdn.net/liuqianspq/article/details/81868283 1.阳光明媚的下午,我在写CRUD,让数据传到前端的时候,解析的时候报错了 ...
- c#编码注释
1 目录 2 前言... 3 2.1 编写目的... 3 2.2 适用范围... 4 3 命名规范... 4 3.1 命名约 ...
- C typedef、#define
参考链接:https://www.runoob.com/cprogramming/c-typedef.html 作用 typedef是用来为数据类型(可以是各种数据类型,包括自己定义的数据类型如结构体 ...
- Java生鲜电商平台-物流动态费率、免运费和固定运费设计与架构
Java生鲜电商平台-物流动态费率.免运费和固定运费设计与架构 说明:物流配送环节常见的有包邮,免运费,或者偏远地区动态费率,还存在一些特殊的情况,固定费率,那么如何进行物流的架构与设计呢? 运费之困 ...
- JavaScript中的 JSON 和 JSONP
JSON 和 JSONP JSONP是一种发送JSON数据的方法,无需担心跨域问题.JSONP不使用该XMLHttpRequest对象.JSONP使用<script>标签代替.由于跨域策略 ...
- 阿里云 centos7 安装MySQL8.0.13
1.下载MySQL安装包(这里是有技巧的,说不定我这时写这个的时候版本还是你看到时的旧版本了,如果已经不是8.0了,可以根据这样来 下新版本) 先进入官网 再将这两者一结合,就是最新版本的了 所以 [ ...