题目:制造括号序列

难度:Medium

题目内容

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

翻译

给定n对括号,写一个函数来生成所有格式正确的括号组合。

For example, given n = 3, a solution set is:

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

我的思路:这应该是典型的卡特兰数的应用的一种吧,对于这种输出所有**的可能组合,在一眼看不出来的情况下应该考虑卡特兰数,就是f(n) = f(0)f(n-1) + f(1)f(n-2) + ... + f(n-1)f(0),在这个题目上应该就是说,首先有n个括号,一共2n个符号,最左边的符号只能为"("并且与其搭配的右括号只能出现在 2i 的位置,所以此时第一个括号把整个序列分成两部分 (2~2i-1) 与后面的所有,这两个部分还能继续往下分,所以有此公式 :  f(n) = ∑ f(i)f(n-1-i)

    确定是卡特兰数之后,一般考虑使用递归法。

  1. public List<String> generateParenthesis(int n) {
  2. List<String> ans = new ArrayList();
  3. if (n == 0) {
  4. ans.add("");
  5. } else {
  6. for (int i = 0; i < n; i++)
  7. for (String in: generateParenthesis(i))
  8. for (String out: generateParenthesis(n-1-i))
  9. ans.add("(" + in + ")" + out);
  10. }
  11. return ans;
  12. }

我的复杂度:  时间:O(2n ! / (n!(n+1)))  空间:O(2n ! / (n!(n+1))) 递归次数就是计算次数,就是卡特兰数的计算公式。

编码过程中遇见问题:

1、在写遍历 in , 与 out 的时候,一开始是还写了个List<String> 来接函数结果,后来参考了下答案上面,才想着对于后面用不着的list可以直接使用foreach遍历

参考答案代码

  1. public List<String> generateParenthesis(int n) {
  2. List<String> ans = new ArrayList();
  3. backtrack(ans, "", 0, 0, n);
  4. return ans;
  5. }
  6.  
  7. public void backtrack(List<String> ans, String cur, int open, int close, int max){
  8. if (cur.length() == max * 2) {
  9. ans.add(cur);
  10. return;
  11. }
  12.  
  13. if (open < max)
  14. backtrack(ans, cur+"(", open+1, close, max);
  15. if (close < open)
  16. backtrack(ans, cur+")", open, close+1, max);
  17. }

参考答案复杂度:时间:O(2n ! / (n!(n+1)))  空间:O(2n ! / (n!(n+1)))

参考答案思路: 使用了另外使用了一个方法,没有用卡特兰数的思想,而是使用了经典的递归思想“走一步看一步”,使不了解卡特兰数的人更容易看懂:

每要添加一个符号的时候都分两种情况。

    a、如果已开的括号数“(”小于要打开的括号数,并且再打开一个括号“+(”,将已开括号数++,并调用下一层;

    b、关闭括号数“)”小于已经打开括号数,则将关闭一个括号“+)”,将关闭数++,并调用下一层。

最后当str的长度为n的2倍时,把它加入结果集并返回。

这样一来每一种情况也能全部考虑到。

LeetCode第[22]题(Java):Generate Parentheses的更多相关文章

  1. 【LeetCode每天一题】Generate Parentheses(创造有效的括弧)

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

  2. Leetcode之回溯法专题-22. 括号生成(Generate Parentheses)

    Leetcode之回溯法专题-22. 括号生成(Generate Parentheses) 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合. 例如,给出 n ...

  3. LeetCode第[18]题(Java):4Sum 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...

  4. LeetCode第[1]题(Java):Two Sum 标签:Array

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  5. LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2

    题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...

  6. LeetCode第[1]题(Java):Two Sum (俩数和为目标数的下标)——EASY

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  7. LeetCode 22. 括号生成(Generate Parentheses)

    22. 括号生成 22. Generate Parentheses 题目描述 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合. 例如,给出 n = 3,生成结 ...

  8. LeetCode第[20]题(Java):Valid Parentheses

    题目:有效的括号序列 难度:Easy 题目内容: Given a string containing just the characters '(', ')', '{', '}', '[' and ' ...

  9. LeetCode第[4]题(Java):Median of Two Sorted Arrays 标签:Array

    题目难度:hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median ...

随机推荐

  1. ubuntu搭建java web环境

    java web环境即jdk+tomcat+mysql jdk:http://www.oracle.com/technetwork/java/javase/downloads/index.html t ...

  2. cpp中文乱码

    中文乱码 [root@test mediaStudio]# g++ testCgi.cpp [root@test mediaStudio]# ./a.out Content-type:text/htm ...

  3. nodejs unit test related----faker-cli, sinonjs, mock/stub

    http://www.tuicool.com/articles/rAnaYvn http://www.tuicool.com/articles/Y73aYn (contrast stub and mo ...

  4. 剑指Offer——从尾到头打印链表

    题目描述: 输入一个链表,从尾到头打印链表每个节点的值. 分析: 方法1:利用栈的性质,先从头到尾遍历链表每个节点的值存入栈中,最后一个一个出栈顺序便是从尾到头的. 方法2:直接从头到尾遍历链表存储节 ...

  5. ugui中实现圆形按钮

    实现圆形按钮,原本是使用 alphHitTestMinimumThreshold 改成重载IsRaycastLocationValid来实现,直接贴代码 using UnityEngine; usin ...

  6. 使用idea的条件断点快速定位注解的处理类

    看代码时会碰到注解的处理类难定位的情况,比如spring的某个注解我们想知道到底是谁在处理他,他起什么作用,通过普通的代码搜索功能不容易找到,比如好用的方法就是条件断点. 比如下断:Accessibl ...

  7. Python迭代对象、迭代器、生成器

    在了解Python的数据结构时,容器(container).可迭代对象(iterable).迭代器(iterator).生成器(generator).列表/集合/字典推导式(list,set,dict ...

  8. Linux安装redis数据库及添加环境变量

    1.下载安装包 [root@localhost opt]# yum install wget [root@localhost opt]# wget http://download.redis.io/r ...

  9. tornado requesthandler可以重写的方法

    一 :RequestHandler 一般我们继承tornado.web.RequestHandler 1,RequestHandler.initialize()一般用于初始化,第三个字典参数传入 cl ...

  10. 用仿ActionScript的语法来编写html5——第六篇,TextField与输入框

    一,对比1,html5中首先看看在html5的canvas中的文字显示 var canvas = document.getElementById("myCanvas"); var ...