题目:制造括号序列

难度: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. 第二课补充01——redis-cli命令行详解、string类型、list类型、hash类型命令操作详解

    一. redis-cli命令行参数 1.-x参数:从标准输入读取一个参数: [问题] [解决] 因为echo命令是默认带有回车\n的,不带回车需要echo –n命令: echo -n "ha ...

  2. emo前端

    1 点击按钮可以在form中添加input控件,以name给input编号,然后点击按钮ajax上传表单,在回调函数中弹框显示结果: <form id="newfriends" ...

  3. Redis配置文件的使用

    Redis基本配置 常规配置 进到配置文件下 vi /etc/redis.conf 写入配置项 port 1111 # 配置端口号 daemonize yes # 是否后台运行 daemonize y ...

  4. CNI bridge 插件实现代码分析

    对于每个CNI 插件在执行函数cmdAdd之前的操作是完全一样的,即从环境变量和标准输入内读取配置.这在http://www.cnblogs.com/YaoDD/p/6410725.html这篇博文里 ...

  5. mysql多条更新

    最近在完成MySql项目集成的情况下,需要增加批量更新的功能,根据网上的资料整理了一下,很好用,都测试过,可以直接使用. mysql 批量更新共有以下四种办法 1..replace into 批量更新 ...

  6. pandas(五)处理缺失数据和层次化索引

    pandas用浮点值Nan表示浮点和非浮点数组中的缺失数据.它只是一个便于被检测的标记而已. >>> string_data = Series(['aardvark','artich ...

  7. 使用 10046 查看执行计划并读懂 trace 文件

    查看 sql 执行计划的方法有许多种, 10046 事件就是其中的一种. 与其他查看 sql 执行计划不同, 当我们遇到比较复杂的 sql 语句, 我们可以通过 10046 跟踪 sql 得到执行计划 ...

  8. str()和repr()(以及``操作符)

    内建函数str()和repr()或反引号操作符(``)可以方便的获取字符串. str它会把值转换为合理形式的字符串,可读性更好,同时对用户来说更加友好. repr它会创建一个字符串,以合法的Pytho ...

  9. sqlserver建立相同的表结构

    select * into purpose from source 来自为知笔记(Wiz)

  10. ipv6被拒的解决方法

    A,检测服务器是否支持ipv6连接 用mac 搭建IPv6环境测试,只能测试客户端到mac这段网络正常,但是mac到服务器还是IPv4的,所以没有办法测试服务器的IPv6是否正常.可以用手机打开2)步 ...