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 ...
随机推荐
- docker使用镜像报错:standard_init_linux.go:211: exec user process caused “exec format error“
在服务器使用镜像运行代码时出现了该报错.使用了docker run 后,由于是刚接触docker,不知道是什么原因.经网上查阅资料后,了解到原来有可能是我的镜像架构和机器架构不一致. 使用 docke ...
- [转]vue-router动态添加路由的方法,addRouter添加路由,提示:Duplicate named routes definition
问题描述:在做使用vue-router动态添加路由的方法,addRouter添加,使用 console.log(this.$router.options.routes) 打印对象,发现添加成功,但是一 ...
- C Primer Plus 第6版 第四章 编程练习参考答案
编译环境VS Code+WSL GCC 源码请到文末下载 /*第1题*************************/ #include<stdio.h> int main() { ch ...
- 记录使用socket.io的使用
今天记录一下node.js的egg框架搭建的socket.io,前端联合使用 首先得引入socket.io的js,我这边是用的下载到本地的一个js 引入:const io = require('../ ...
- Solution Set - “谁将重力悬空,坠入一场蔚蓝的梦”
目录 0.「NOI Simu.」皮配 1.「BZOJ #4671」异或图 2.「CF 1158F」Density of subarrays 3.「CF 794G」Replace All 4.「UR # ...
- 通过WebView2获取HTTP-only cookie
通过WebView2获取HTTP-only cookie可以使用`WebView2.CookieManager`类的方法.以下是一个示例代码,演示如何获取HTTP-only cookie: using ...
- SpringBoot(二) - 核心配置文件 (+ 邮件发送 和 短信发送)
1.application.properties 和 application.yml 配置文件格式区别 1.1 文件格式 application.properties # 端口号 server.por ...
- bootwiki-Elasticsearch教程
https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html Elasticsearch教程 Elasticse ...
- Fo-dicom通过C-store方式发送图片
1 using Dicom.Network; 2 using System; 3 using System.Collections.Generic; 4 using System.Linq; 5 us ...
- 金山毒霸提示这是高危入侵行为taskeng.exe
如果安装了金山毒霸之后经常会弹窗提示:这是高位入侵行为.行为发起taskeng.exe.可疑进程regsvr32.EXE,可疑路径antivirus.php,如下入所示: 可以直接点击"阻止 ...