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 ParenthesesValid Parenthesis String, Remove Invalid ParenthesesDifferent Ways to Add ParenthesesValid 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

类似题目:

Remove Invalid Parentheses

Different Ways to Add Parentheses

Longest Valid Parentheses

Valid Parentheses

Score of Parentheses

Valid Parenthesis String

参考资料:

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 生成括号的更多相关文章

  1. [leetcode]22. Generate Parentheses生成括号

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  2. [CareerCup] 9.6 Generate Parentheses 生成括号

    9.6 Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-p ...

  3. 22.Generate Parentheses[M]括号生成

    题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...

  4. generate parentheses(生成括号)

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  5. [LintCode] Generate Parentheses 生成括号

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  6. [LeetCode]22. Generate Parentheses括号生成

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  7. [LeetCode] Generate Parentheses 生成括号

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  8. 22. Generate Parentheses生成指定个括号

    生成指定个数的括号,这些括号可以相互包括,但是一对括号的格式不能乱(就是配对的一个括号的左括号要在左边,右括号要在右边) 思维就是从头递归的添加,弄清楚什么时候要添加左括号,什么时候添加右括号 有点像 ...

  9. LeetCode 22 Generate Parentheses(找到所有匹配的括号组合)

    题目链接 : https://leetcode.com/problems/generate-parentheses/?tab=Description   给一个整数n,找到所有合法的 () pairs ...

随机推荐

  1. HTML+css基础 css的几种形式 css选择器的两大特性

    3.外联样式 css选择器的两大特性 1.继承性:所有跟文本字体有关的属性都会被子元素继承.且权重是0000. 2.层叠性:就是解决选择器权重大小的一种能力,就是看那个选择器的权重大.谁的权重大听谁的 ...

  2. Docker 下开发安装hyperf

    Docker 下开发hyperf # 下载并运行 hyperf/hyperf 镜像,并将镜像内的项目目录绑定到宿主机的 /tmp/skeleton 目录 docker run -v /tmp/skel ...

  3. Window权限维持(十):Netsh Helper DLL

    Netsh是Windows实用程序,管理员可以使用它来执行与系统的网络配置有关的任务,并在基于主机的Windows防火墙上进行修改.可以通过使用DLL文件来扩展Netsh功能.此功能使红队可以使用此工 ...

  4. 3、Ext.NET 1.7 官方示例笔记-表单

    表单[Form],就是向客户收集资料的窗口,用户在表单填写好各种信息,然后提交到服务器,服务器接收并保存到数据库里. 表单的字段类型很多,我们从最简单的开始吧. 1.1 .先开始组合框吧(ComboB ...

  5. Locust 接口性能测试 - 转载一 (后期熟悉实践自己出一套完整的)

    转载大佬   ,.. 另外一篇:https://www.cnblogs.com/imyalost/p/9758189.html记录一下接口性能测试的学习 先熟悉一下概念: Locust是使用Pytho ...

  6. STorM32 BGC三轴云台控制板电机驱动电路设计(驱动芯片DRV8313)

    1  序言 相信对云台有兴趣的小伙伴对STorM32 BGC这块云台控制板并不陌生,虽说这块控制板的软件已经不再开源,但是在GitHub上依旧可以找到两三个版本的代码,而硬件呢我们也可以从Olliw( ...

  7. GALAXY OJ NOIP2019联合测试1-总结

    概要 本次比赛考的不是很好,400分的题只拿了180分...(失误失误) 题目 T1:数你太美(预期100 实际60) 题目大意: 在两个序列中找两个最小的数进行组合,使这个最小整数最小. 解析: 只 ...

  8. wpf DATAgrid模板中button 命令绑定以及命令参数绑定

    场景:视频上传功能,上传列表使用DataGrid控件,视频有不同的状态对应不同的操作,DataGrid中最后一列为操作列,里面是Button控件.希望点击Button后执行对应的操作,但是设置Butt ...

  9. 图解Java数据结构之稀疏数组

    在编程中,算法的重要性不言而喻,没有算法的程序是没有灵魂的.可见算法的重要性. 然而,在学习算法之前我们需要掌握数据结构,数据结构是算法的基础. 我在大学的时候,学校里的数据结构是用C语言教的,因为对 ...

  10. 为什么重复的GET请求变慢了?

    最近在研究慢请求监控的问题,写了一个简单的测试代码:在网页端(index.html)通过fetch函数向服务端获取数据,然后打印请求耗时. function requestData() { let s ...