问题:

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:

[

"((()))",

"(()())",

"(())()",

"()(())",

"()()()"

]

官方难度:

Medium

翻译:

合并n个括号,生成所有n个括号组成的合理序列。

例子:

给定n=3,解集为

[

"((()))",

"(()())",

"(())()",

"()(())",

"()()()"

]

方法一:

  1. 初始的思想,考虑使用递归,每次优先获取n-1个括号所有情况下的集合,然后插入新的括号。
  2. 递归的终点是n=1,返回包含一个元素“()”的集合。
  3. 每次先加“(”,在第一个位置和一个“)”的下一个位置,插入左括号。
  4. 然后加右括号,从加入的左括号开始,统计左括号和右括号的个数,在左括号个数大于右括号个数的情况下,才可以加入右括号。
  5. 不难发现,虽然已经极力避免了,但是这种方法会出现很多的重复情况,所以需要一个Set集合去重,在递归结束之后,转化成List集合返回。

方法一的解题代码:

     // 根据n-1的情况增加括号
public static List<String> method(int n) {
List<String> list = new ArrayList<>(getPharentheses(n));
return list;
} private static Set<String> getPharentheses(int n) {
Set<String> set = new HashSet<>();
if (n == 1) {
set.add("()");
} else {
Set<String> last = getPharentheses(n - 1);
for (String s : last) {
String s1 = "(" + s;
int l1 = 0;
int r1 = 0;
for (int j = 1; j < s1.length(); j++) {
if (s1.charAt(j) == '(') {
l1++;
} else {
r1++;
}
// 这里有重复的可能性
if (l1 > r1) {
set.add(s1.substring(0, j + 1) + ")" + s1.substring(j + 1));
}
}
// 先加左括号
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == ')') {
String str = s.substring(0, i + 1) + "(" + s.substring(i + 1);
// 左右括号计数
int l = 0;
int r = 0;
for (int j = i + 1; j < str.length(); j++) {
if (str.charAt(j) == '(') {
l++;
} else {
r++;
}
// 这里有重复的可能性
if (l > r) {
set.add(str.substring(0, j + 1) + ")" + str.substring(j + 1));
}
}
}
}
}
}
return set;
}

method

方法二:

  1. 显而易见,如果通过某种算法,没有重复的情况产生,那么方法的执行效率一定会快很多。
  2. 假设n=3。先加上所有的左括号,“(((”,那么右括号的可能性只有一个,那就是“((()))”。
  3. 然后回退一步,少加一个左括号,加上一个右括号,之后再加上这个左括号,会形成以下形式“(()())”。
  4. 后加的左括号再回退一步“(())()”。依次类推,直到这个左括号不能再加为止,回退至第一步,在一开始回退2个左括号,得到以下2种形式“()(())”和“()()()”。
  5. 发现回退的左括号为n时,结束。
  6. 解题的代码形式很简单,但是逻辑比较难捋通顺。
  7. 注意入参检查。

方法二的解题代码:

     public static List<String> generateParenthesis(int n) {
if (n < 1) {
throw new IllegalArgumentException("Input error");
}
List<String> list = new ArrayList<>();
generate(n, n, "", list);
return list;
} // 先加所有左括号,遍历所有可能性,然后回退一个左括号,依次类推
private static void generate(int left, int right, String current, List<String> list) {
// 先加左括号
if (left > 0) {
generate(left - 1, right, current + "(", list);
}
if (right > 0 && right > left) {
generate(left, right - 1, current + ")", list);
}
if (left == 0 && right == 0) {
list.add(current);
}
}

generateParenthesis

相关链接:

https://leetcode.com/problems/generate-parentheses/

https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/medium/Q022.java

PS:如有不正确或提高效率的方法,欢迎留言,谢谢!

No.022:Generate Parentheses的更多相关文章

  1. LeetCode OJ:Generate Parentheses(括号生成)

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

  2. LeetCode第[22]题(Java):Generate Parentheses

    题目:制造括号序列 难度:Medium 题目内容: Given n pairs of parentheses, write a function to generate all combination ...

  3. LeetCode 022 Generate Parentheses

    题目描述:Generate Parentheses Given n pairs of parentheses, write a function to generate all combination ...

  4. 72. Generate Parentheses && Valid Parentheses

    Generate Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', ...

  5. Generate Parentheses

    Generate Parentheses Given n pairs of parentheses, write a function to generate all combinations of ...

  6. [LintCode] Generate Parentheses 生成括号

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

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

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

  8. 【题解】【排列组合】【回溯】【Leetcode】Generate Parentheses

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

  9. leetcode022. Generate Parentheses

    leetcode 022. Generate Parentheses Concise recursive C++ solution class Solution { public: vector< ...

随机推荐

  1. 【VC++技术杂谈002】打印技术之获取及设置系统默认打印机

    本文主要介绍如何获取以及设置系统的默认打印机. 1.获取系统中的所有打印机 获取系统中的所有打印机可以使用EnumPrinters()函数,该函数可以枚举全部的本地.网络打印机信息.其函数原型为: B ...

  2. C# MVC 项目下的路由配置-RouteConfig

    1. 设置备份全局路径下的路由 目的,我们在网站中域名后面输入参数,可以跳转到相应的controller,例如:www.innovsys.cn/dd.直后端直接跳转到controller,获取dd参数 ...

  3. 《深入理解 java虚拟机》学习笔记

    java内存区域详解 以下内容参考自<深入理解 java虚拟机 JVM高级特性与最佳实践>,其中图片大多取自网络与本书,以供学习和参考.

  4. KnockoutJS 3.X API 第七章 其他技术(6) 使用“fn”添加自定义函数

    有时,您可能会通过向Knockout的核心值类型添加新功能来寻找机会来简化您的代码. 您可以在以下任何类型中定义自定义函数: 因为继承,如果你附加一个函数到ko.subscribable,它将可用于所 ...

  5. AVEVA Model Data Exchange Exports Structure Models

    AVEVA Model Data Exchange Exports Structure Modelseryar@163.com Use Model Data Exchange Addin to exp ...

  6. The Installation and Compilation of OpenCASCADE

    OpenCASCADE的编译 The Installation and Compilation of OpenCASCADE eryar@163.com 一. 安装OpenCASCADE 可以从Ope ...

  7. 万能Adapter以及ViewHolder性能优化

    //CommonAdapter import android.content.Context; import android.widget.BaseAdapter; import java.util. ...

  8. 用 namspace 隔离 DHCP 服务 - 每天5分钟玩转 OpenStack(90)

    Neutron 通过 dnsmasq 提供 DHCP 服务,而 dnsmasq 如何独立的为每个 network 服务呢? 答案是通过 Linux Network Namespace 隔离,本节将详细 ...

  9. 在ubuntu上面配置nginx实现反向代理和负载均衡

    上一篇文章(http://www.cnblogs.com/chenxizhang/p/4684260.html),我做了一个实验,就是利用Visual Studio,基于Nancy框架,开发了一个自托 ...

  10. css3实现的动画效果

    在线演示:莲花盛开 在线演示:忙碌光标效果 在线演示:发光效果