LeetCode第[22]题(Java):Generate Parentheses
题目:制造括号序列
难度: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的更多相关文章
- 【LeetCode每天一题】Generate Parentheses(创造有效的括弧)
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- Leetcode之回溯法专题-22. 括号生成(Generate Parentheses)
Leetcode之回溯法专题-22. 括号生成(Generate Parentheses) 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合. 例如,给出 n ...
- 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 + ...
- 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 ...
- LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2
题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...
- 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 ...
- LeetCode 22. 括号生成(Generate Parentheses)
22. 括号生成 22. Generate Parentheses 题目描述 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合. 例如,给出 n = 3,生成结 ...
- LeetCode第[20]题(Java):Valid Parentheses
题目:有效的括号序列 难度:Easy 题目内容: Given a string containing just the characters '(', ')', '{', '}', '[' and ' ...
- 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 ...
随机推荐
- VS2008里的代码如何格式化
选中要格式化的代码, 先按Ctrl+K 再按Ctrl+F 从菜单中也可以 "编辑"->"高级"->"设置文档的格式Ctrl+K Ctrl+ ...
- A4纸网页打印中对应像素的设定和换算
最近开发项目时遇到了网页打印的问题,这是问题之二,打印宽度设置 在公制长度单位与屏幕分辨率进行换算时,必须用到一个DPI(Dot PerInch)指标. 经过我仔细的测试,发现了网页打印中,默认采用 ...
- MongoDB-1:安装和配置
一.简介 MongoDB一种非关系型数据库(NoSql),是一种强大.灵活.可扩展的数据存储方式,因为MongoDB是文档模型,自由灵活很高,可以让你在开发过程中畅顺无比,对于大数据量.高并发.弱事务 ...
- Android项目使用Ant多渠道打包(最新sdk)
参考文章: http://blog.csdn.net/liuhe688/article/details/6679879 http://www.eoeandroid.com/thread-323111- ...
- Linux ssh面密码登录
1.生成自己的公钥和私钥 ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa 进入~/.ssh目录看多了两个文件:id_rsa id_rsa.pub 其中一个是公钥一 ...
- 利用Docker快速部署Oracle环境
工作中需要频繁使用Oracle环境,但是每次搭建起来比较消耗时间,本想通过虚拟机模板的方式来快速安装oracle vm,但是每次改ip等环境也很耗时,因此想到docker中有没有已经做好的images ...
- Top 10 Uses For A Message Queue
We’ve been working with, building, and evangelising message queues for the last year, and it’s no se ...
- CentOS中nginx负载均衡和反向代理的搭建
1: 修改centos命令行启动(减少内存占用): vim /etc/inittab :initdefault: --> 修改5为3 若要界面启动使用 startx 2:安装jdk )解压:jd ...
- PAT 天梯赛 L1-047. 装睡 【水】
题目链接 https://www.patest.cn/contests/gplt/L1-047 AC代码 #include <iostream> #include <cstdio&g ...
- Educational Codeforces Round 11A. Co-prime Array 数学
地址:http://codeforces.com/contest/660/problem/A 题目: A. Co-prime Array time limit per test 1 second me ...