题目:制造括号序列

难度: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:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

我的思路:这应该是典型的卡特兰数的应用的一种吧,对于这种输出所有**的可能组合,在一眼看不出来的情况下应该考虑卡特兰数,就是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)

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

     public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList();
if (n == 0) {
ans.add("");
} else {
for (int i = 0; i < n; i++)
for (String in: generateParenthesis(i))
for (String out: generateParenthesis(n-1-i))
ans.add("(" + in + ")" + out);
}
return ans;
}

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

编码过程中遇见问题:

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

参考答案代码:

     public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList();
backtrack(ans, "", 0, 0, n);
return ans;
} public void backtrack(List<String> ans, String cur, int open, int close, int max){
if (cur.length() == max * 2) {
ans.add(cur);
return;
} if (open < max)
backtrack(ans, cur+"(", open+1, close, max);
if (close < open)
backtrack(ans, cur+")", open, close+1, max);
}

参考答案复杂度:时间: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. delphi ---break,exit,continue等跳出操作的区别

    1.break 强制退出最近的一层循环(注意:只能放在循环里:而且是只能跳出最近的一层循环),用于从for.while.repeat语句中强制退出 2.continue 用于从for.while.re ...

  2. 微信公众号 待发货-物流中-已收货 foreach break continue

    w <?php $warr = array(1,2,3); $w_break = 0; foreach($warr AS $w){ if($w==2)break; $w_break += $w; ...

  3. MFC DLL获取当前路径

    .首先定义此获取模块的静态方法 #if _MSC_VER >= 1300 // for VC 7.0 // from ATL 7.0 sources #ifndef _delayimp_h ex ...

  4. CSS 快速入门

    特点: CSS 将网页内容和显示样式进行分离,提高了显示效果的功能. CSS 和 html 相结合的四种方式: style 属性的方式 每个 html 标签中都有一个 style 样式属性, 该属性的 ...

  5. 洛谷 P4451 [国家集训队]整数的lqp拆分

    洛谷 这个题目是黑题,本来想打表的,但是表调不出来(我逊毙了)! 然后随便打了一个递推,凑出了样例, 竟然. 竟然.. 竟然... A了!!!!!!! 直接:\(f[i]=f[i-1]*2+f[i-2 ...

  6. Django框架-模板系统

    来看一段代码 def current_datetime(request): now = datetime.datetime.now() html = "<html><bod ...

  7. 访问HDFS报错:org.apache.hadoop.security.AccessControlException: Permission denied

    import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apac ...

  8. sql server性能调优

    转自:https://www.cnblogs.com/woodytu/tag/%E6%80%A7%E8%83%BD%E8%B0%83%E4%BC%98%E5%9F%B9%E8%AE%AD/defaul ...

  9. Kotlin开发Android笔记

    外国人写的一个天气预报的例子,最后有源码下载地址,初学者可以研读一下 http://blog.csdn.net/true100/article/category/6257988 1:Kotlin介绍及 ...

  10. 用仿ActionScript的语法来编写html5——第五篇,Graphics绘图

    用仿ActionScript的语法来编写html5——第五篇,Graphics绘图 canvas本身就是一个Graphics,可以直接进行绘图在actionscript里面,每个Sprite都有一个G ...