22. Generate Parentheses--求n对括号组成可以组成的全部有效括号序列
描述:
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
我的老实人+不择手段算法:
let cache = {};
var generateParenthesis = function(n) {
暴力枚举
if(n==1){
return ['()'];
}
if(cache[n])
return cache[n];
let start = '',result = [];
for(let i = 0; i < n; i++){
start +='()';
}
result.push(start);
for(let i = 1,l=start.length; i < n;i++){
let move = generateParenthesis(start.slice(0,i*2).length /2),
holdOn = generateParenthesis(start.slice(i*2).length/2);
move.forEach((item)=>{
holdOn.forEach((holdOn) => {
for( let j = 0,subLength = holdOn.length; j < subLength; j += 2){
result.push( holdOn.slice(0,j+1) + item + holdOn.slice(j+1) )
}
})
})
}
for(let i = 0,l=result.length; i < l; i++){
if(result.indexOf(result[i])!==result.lastIndexOf(result[i])){
result.splice(i,1);
i--;
}
}
cache[n] = result;
return result;
}
思路:给定n对括号,可以先构造一个模板,然后在这个模板中,通过移动左边1,2,...,n-1 个括号到右边的括号里面,这样就可以构造出所有可能的有效序列了,
比分说: n = 3, 那么我们可以先构造出一个模板 ()()(),而后通过移动左边的1,2个括号到右边的2,1个括号构成的序列的括号里边的位置,那么就可以构造出其他有效序列了,而这里边必须注意的是移动左边的括号往右边的括号里边放的时候,左右两个子序列也会有各自的排序方法,所以需要递归的先求出左右序列的所有排列可能,而后再进行插入操作。
事情还没完,这样左右两边都列出可能的排列之后,肯定会发生重复,所以最后我又进行了一个数组去重,真是不可原谅,最后提交的时候抛出了308ms惊人的成绩。这还是在用了cache缓存一定子序列的情况下跑的。
然后要着重贴一下官方的解答下面的一个递归算法,
var generateParenthesis = function(n) {
/* 保持 左右平衡 */
let result = [],
produce = (curStr,left,right,curNums) => {
if( (left == curNums )&& (right == curNums) ){
result.push(curStr);
return;
}
if( left < curNums){
produce(curStr+'(',left +1 ,right,curNums);
}
if( right < left){
produce(curStr+')',left,right+1,curNums);
}
};
produce('',0,0,n);
return result;
};
这个算法其实更暴力,妙在使用递归和保持左右括号平衡的方法将一个看似复杂的问题简化了,我们走一遍流程哈,假如 n = 3对,刚开始 肯定是左半边括号加,
然后进入递归
此时left为1,继续
此时left为2,继续
此时left为3了,右半括号开始加,
此时right为1,继续
此时right为2,继续递归
此时right为3,
result里边push进((()))
最后一层函数返回
倒数第二层返回,直到返回到left为2时的状态
进入到 第三个if里边,这时候 curStr = ((),继续递归
......
直到结束。
我是真的觉得这个算法很妙,确实很钦佩第一个想出此种算法的人,妙极!因为递归,所以函数上下文可以保留函数的环境,也就是保存了‘(’和‘)’的各种排列,并且是平衡的,只要平衡(即左右括号数列相等)就是有效的。
高手高手!
22. Generate Parentheses--求n对括号组成可以组成的全部有效括号序列的更多相关文章
- [Leetcode][Python]22: Generate Parentheses
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 22: Generate Parentheseshttps://oj.leet ...
- 刷题22. Generate Parentheses
一.题目说明 这个题目是22. Generate Parentheses,简单来说,输入一个数字n,输出n对匹配的小括号. 简单考虑了一下,n=0,输出"";n=1,输出" ...
- 22. Generate Parentheses(ML)
22. Generate Parentheses . Generate Parentheses Given n pairs of parentheses, write a function to ge ...
- [LeetCode]22. Generate Parentheses括号生成
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- 22.Generate Parentheses[M]括号生成
题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...
- LeetCode 22 Generate Parentheses(找到所有匹配的括号组合)
题目链接 : https://leetcode.com/problems/generate-parentheses/?tab=Description 给一个整数n,找到所有合法的 () pairs ...
- 22. Generate Parentheses生成指定个括号
生成指定个数的括号,这些括号可以相互包括,但是一对括号的格式不能乱(就是配对的一个括号的左括号要在左边,右括号要在右边) 思维就是从头递归的添加,弄清楚什么时候要添加左括号,什么时候添加右括号 有点像 ...
- LeetCode OJ 22. Generate Parentheses
题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...
- 【LeetCode】22. Generate Parentheses (2 solutions)
Generate Parentheses Given n pairs of parentheses, write a function to generate all combinations of ...
- 22. Generate Parentheses (recursion algorithm)
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
随机推荐
- rsync+ssh同步备份文件
定期对web代码或重要的文件做同步异地服务器备份,防止服务器故障严重磁盘损坏时文件丢失的问题. 备份服务器:192.168.200.134 目标服务器:192.168.201.65 rsync同步命令 ...
- Java子线程无法获取Attributes的解决方法
在Java多线程编程中,开发者经常会遇到子线程无法获取主线程设置的Attributes的问题.Attributes通常用于存储与当前线程相关的数据,尤其在Web应用中,它们常用于请求上下文的管理.然而 ...
- 【量化读书笔记】【打开量化投资的黑箱】CH.05. 交易成本模型
交易是有成本的,除非有足够的理由,否则便不应该进行交易. 交易的原因 增加盈利的期望值 降低亏损的期望值 对交易成本的估计 过低,会导致交易过于频繁,损失扩大. 过高,导致交易次数少,持仓时间过长. ...
- ConcurrentLinkedQueue深度源码剖析
在Java的并发包中,存在着许多高效的并发工具类,它优于synchronized关键字,在JDK中提供了一个ConcurrentLinkedQueue工具类实现了高效的并发读写工具类,该工具类具有很高 ...
- 2025-01-15:执行操作可获得的最大总奖励 Ⅰ。用go语言,给定一个整数数组 rewardValues,其中包含 n 个代表奖励值的数字。 你开始时的总奖励 x 为 0,并且所有下标都是未标记状
2025-01-15:执行操作可获得的最大总奖励 Ⅰ.用go语言,给定一个整数数组 rewardValues,其中包含 n 个代表奖励值的数字. 你开始时的总奖励 x 为 0,并且所有下标都是未标记状 ...
- PICO 避坑指南
1. Win10 不需要串口驱动,使用PICO W之前先刷固件pico w的固件 micropython-firmware-pico-w-290622.rar 刚开始 刷的固件不对,一直无法识别串口. ...
- FailFast机制-抛出 java.util.ConcurrentModificationException(保证并发访问时集合的完整性,内部结构变化的防护措施)
- 创建多线程的方式二:实现Runnable接口
/** * 创建多线程的方式二:实现Runnable接口 * 1. 创建一个实现了Runnable接口的类 * 2. 实现类去实现Runnable中的抽象方法:run() * 3. 创建实现类的对 ...
- bullyBox pg walkthrough Intermediate
nmap 发现80 和 22端口 访问80 端口发现 跳转 http://bullybox.local/ 在/etc/hosts 里面加上这个域名 dirsearch 扫描的时候发现了.git泄露 用 ...
- 银杏叶也是yxy
今年下半年(9月后)第一个使我震撼而狂喜的书籍,金阁寺. 翻译是林少华.他翻译这个可比村上春树好多了 一切都像梦寐一般,一切都如此完美 完美的结构,完美的心理叙述,撕心裂肺的景色描写 战后无限的虚无与 ...