问题:

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. C# BS消息推送 SignalR Hubs环境搭建与开发(二)

    1. 前言 本文是根据网上前人的总结得出的. 环境: SignalR2.x,VS2015,Win10 2. 开始开发 1)新建一个MVC项目,叫做SignalRDemo 2)安装SignalR包 In ...

  2. Atitit  补充说明 sql知识图谱与线路图attilax总结补充说明

    Atitit  补充说明 sql知识图谱与线路图attilax总结补充说明 1. 常见编程语言的分类  :命令式语言.函数式语言.逻辑语言1 1.1. 按照编程语言的代际划分,又2gl,3gl,4gl ...

  3. Android-异步任务-AsyncTask

    什么是异步任务? 异步任务就是开一个子线程,然后让它去跑,它跑完了就会回来告诉你说,它跑完了,这是结果.这和Java中的回调差不多.我们在OKHttp中很长见到的 onSuccess() 和 onEr ...

  4. Entity Framework Core 1.1 Preview 1 简介

    实体框架核心(EF Core)是Entity Framework的一个轻量级,可扩展和跨平台版本. 10月25日,Entity Framework Core 1.1 Preview 1发布了. 升级到 ...

  5. MVC遇上bootstrap后的ajax表单模型验证

    MVC遇上bootstrap后的ajax表单验证 使用bootstrap后他由他自带的样式has-error,想要使用它就会比较麻烦,往常使用jqueyr.validate的话只有使用他自己的样式了, ...

  6. Android初级教程_获取Android控件的宽和高

    转载:http://blog.csdn.net/johnny901114/article/details/7839512 我们都知道在onCreate()里面获取控件的高度是0,这是为什么呢?我们来看 ...

  7. Android图片选择器

    1.概述 应公司项目需求,要做一个图片选择器,网上搜索了一些源码,我在别人的基础上进行了修改,另外页面也进行了重整,我的是先加载图片文件夹列表,然后再进入选择图片.            参考博客地址 ...

  8. Cookie/Session机制详解

    会话(Session)跟踪是Web程序中常用的技术,用来跟踪用户的整个会话.常用的会话跟踪技术是Cookie与Session.Cookie通过在客户端记录信息确定用户身份,Session通过在服务器端 ...

  9. javascript模拟继承

    javascript作为前端开发的标配技能,如果不掌握好它的三大特点:1.原型 2.作用域 3. 闭包 ,又怎么可以说你学好了这门语言呢?如果标配的技能都没有撑握好,怎么可以任性的玩耍呢?怎么验证自己 ...

  10. position:fixed和scroll实现div浮动【示例】

    前言 在自己建站的过程中,要实现一个div随滚动条浮动的效果,网上找了些示例不太好用,还是自己动手,丰衣足食,写的不好请大家谅解,毕竟我不是搞前端的,因为自己建站毕竟每一步都必须自己来,这边只是做个记 ...