[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 ...
随机推荐
- Redis 设计与实现,看 SDS(Simple Dynamic String) 感悟
Redis 设计与实现,看 SDS(Simple Dynamic String) 感悟 今天在看 Redis 设计与实现这本书的时候,发现了里面系统定义的数据结构 SDS,中文名为 简单动态字符串.对 ...
- Python getopt 模块
Python getopt 模块 getopt模块,是配合sys.argv使用的一个扩展.他可以接收终端的参数.格式扩展为“-n” 或 “--n”两种类型,下面是具体解释. 使用 improt get ...
- C#工具类SqlServerHelper,基于System.Data.SqlClient封装
源码: using System; using System.Collections.Generic; using System.Data; using System.Linq; using Syst ...
- Win10 手动安装 WSL 并修改默认登录用户为 root
首先要在"程序和功能"里面开启这个服务 然后重启系统使其生效. 然后打开 PowerShell,输入: Invoke-WebRequest -Uri https://aka.ms/ ...
- minggw 安装
windows上如果没有安装 visual studio, 也就是俗称的vs, 在安装一些带有c或者c++代码的Python模块的时候, 会报错Unable to find vcvarsall.bat ...
- string 字符串 的一些使用方法
Java语言中,把字符串作为对象来处理,类String就可以用来表示字符串(类名首字母都是大写的). 字符串常量是用双引号括住的一串字符. 例如:"Hello World" Str ...
- .NET开发框架(六)-架构设计之IIS负载均衡(视频)
前面有关注我们公众号文章的朋友应该都知道,我们的分布式应用服务可以通过Ocelot网关进行负载均衡,这种方式属于应用级别的实现. 而今天我们给大家介绍的是平台级别的实现,并且我们首次使用视频方式进行讲 ...
- body的背景
body的背景 背景background-color:默认border-box 画布canvas 一块区域 背景background-color的画布的特点:(画布大于等于视口) 最小宽度视口宽度 最 ...
- dlopen动态链接库操作
void *dlopen(const char *filename, int flag); //打开一个动态链接库,并返回动态链接库的句柄 char *dlerror(void); void *dls ...
- xcode6新建工程
xcode6中新建空工程 (2014-10-29 13:14:44) 转载▼ 标签: it ios 分类: iOS 升级xcode6之后,直接建立Empty工程后发现,这是太坑,真的是什么都没有啊.只 ...