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:

  1. [
  2. "((()))",
  3. "(()())",
  4. "(())()",
  5. "()(())",
  6. "()()()"
  7. ]
  

在 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++ 解法一:

  1. class Solution {
  2. public:
  3. vector<string> generateParenthesis(int n) {
  4. vector<string> res;
  5. generateParenthesisDFS(n, n, "", res);
  6. return res;
  7. }
  8. void generateParenthesisDFS(int left, int right, string out, vector<string> &res) {
  9. if (left > right) return;
  10. if (left == && right == ) res.push_back(out);
  11. else {
  12. if (left > ) generateParenthesisDFS(left - , right, out + '(', res);
  13. if (right > ) generateParenthesisDFS(left, right - , out + ')', res);
  14. }
  15. }
  16. };

Java 解法一:

  1. public class Solution {
  2. public List<String> generateParenthesis(int n) {
  3. List<String> res = new ArrayList<String>();
  4. helper(n, n, "", res);
  5. return res;
  6. }
  7. void helper(int left, int right, String out, List<String> res) {
  8. if (left < 0 || right < 0 || left > right) return;
  9. if (left == 0 && right == 0) {
  10. res.add(out);
  11. return;
  12. }
  13. helper(left - 1, right, out + "(", res);
  14. helper(left, right - 1, out + ")", res);
  15. }
  16. }

再来看那一种方法,这种方法是 CareerCup 书上给的方法,感觉也是满巧妙的一种方法,这种方法的思想是找左括号,每找到一个左括号,就在其后面加一个完整的括号,最后再在开头加一个 (),就形成了所有的情况,需要注意的是,有时候会出现重复的情况,所以用set数据结构,好处是如果遇到重复项,不会加入到结果中,最后我们再把set转为vector即可,参见代码如下::

n=1:    ()

n=2:    (())    ()()

n=3:    (()())    ((()))    ()(())    (())()    ()()()

C++ 解法二:

  1. class Solution {
  2. public:
  3. vector<string> generateParenthesis(int n) {
  4. unordered_set<string> st;
  5. if (n == ) st.insert("");
  6. else {
  7. vector<string> pre = generateParenthesis(n - );
  8. for (auto a : pre) {
  9. for (int i = ; i < a.size(); ++i) {
  10. if (a[i] == '(') {
  11. a.insert(a.begin() + i + , '(');
  12. a.insert(a.begin() + i + , ')');
  13. st.insert(a);
  14. a.erase(a.begin() + i + , a.begin() + i + );
  15. }
  16. }
  17. st.insert("()" + a);
  18. }
  19. }
  20. return vector<string>(st.begin(), st.end());
  21. }
  22. };

Java 解法二:

  1. public class Solution {
  2. public List<String> generateParenthesis(int n) {
  3. Set<String> res = new HashSet<String>();
  4. if (n == 0) {
  5. res.add("");
  6. } else {
  7. List<String> pre = generateParenthesis(n - 1);
  8. for (String str : pre) {
  9. for (int i = 0; i < str.length(); ++i) {
  10. if (str.charAt(i) == '(') {
  11. str = str.substring(0, i + 1) + "()" + str.substring(i + 1, str.length());
  12. res.add(str);
  13. str = str.substring(0, i + 1) + str.substring(i + 3, str.length());
  14. }
  15. }
  16. res.add("()" + str);
  17. }
  18. }
  19. return new ArrayList(res);
  20. }
  21. }

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. Redis 设计与实现,看 SDS(Simple Dynamic String) 感悟

    Redis 设计与实现,看 SDS(Simple Dynamic String) 感悟 今天在看 Redis 设计与实现这本书的时候,发现了里面系统定义的数据结构 SDS,中文名为 简单动态字符串.对 ...

  2. Python getopt 模块

    Python getopt 模块 getopt模块,是配合sys.argv使用的一个扩展.他可以接收终端的参数.格式扩展为“-n” 或 “--n”两种类型,下面是具体解释. 使用 improt get ...

  3. C#工具类SqlServerHelper,基于System.Data.SqlClient封装

    源码: using System; using System.Collections.Generic; using System.Data; using System.Linq; using Syst ...

  4. Win10 手动安装 WSL 并修改默认登录用户为 root

    首先要在"程序和功能"里面开启这个服务 然后重启系统使其生效. 然后打开 PowerShell,输入: Invoke-WebRequest -Uri https://aka.ms/ ...

  5. minggw 安装

    windows上如果没有安装 visual studio, 也就是俗称的vs, 在安装一些带有c或者c++代码的Python模块的时候, 会报错Unable to find vcvarsall.bat ...

  6. string 字符串 的一些使用方法

    Java语言中,把字符串作为对象来处理,类String就可以用来表示字符串(类名首字母都是大写的). 字符串常量是用双引号括住的一串字符. 例如:"Hello World" Str ...

  7. .NET开发框架(六)-架构设计之IIS负载均衡(视频)

    前面有关注我们公众号文章的朋友应该都知道,我们的分布式应用服务可以通过Ocelot网关进行负载均衡,这种方式属于应用级别的实现. 而今天我们给大家介绍的是平台级别的实现,并且我们首次使用视频方式进行讲 ...

  8. body的背景

    body的背景 背景background-color:默认border-box 画布canvas 一块区域 背景background-color的画布的特点:(画布大于等于视口) 最小宽度视口宽度 最 ...

  9. dlopen动态链接库操作

    void *dlopen(const char *filename, int flag); //打开一个动态链接库,并返回动态链接库的句柄 char *dlerror(void); void *dls ...

  10. xcode6新建工程

    xcode6中新建空工程 (2014-10-29 13:14:44) 转载▼ 标签: it ios 分类: iOS 升级xcode6之后,直接建立Empty工程后发现,这是太坑,真的是什么都没有啊.只 ...