【LeetCode】【动态规划】Generate Parentheses(括号匹配问题)
描述
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路1——DP
设:P[i]表示当n=i的时候括号组合串。 观察规律:我们知道,要形成一个括号的组合,肯定不是凭空产生的,产生一个P[3]的组合,那肯定是把"("和")"分别插在P[2]中间的。
我们假设产生P[3]组合的时候,之前的组合都是正确的,那么通过插入"(",")"肯定会把P[2]分成两个部分(括号内一个,括号外一个)
看似好像有很多插入的方法,但是,其实仔细想想,反正"("得增加一个,由于括号组合的第一一定是"(",为什么不把新增的"("放在开头呢?这样我们就只用考虑")"了
会怎么把P[2]切割就好了,我们知道P[2]的组合有P[0]+P[2],P[1]+P[1],P[2]+P[0],

通过写出前几个可以观察到下面的规律
P[0]= [""]
P[1] = [()] = "("+P[0]+")"+P[0]
P[2] = [()(),(())] = "("+P[0]+")"+P[1] , "("+P[1]+")" +P[0]
P[3] = [()()(),()(()),(())(),(()()),((()))] = "("+P[0]+")"+P[2] , "("+P[1]+")"+P[1], "("+P[2]+")" +P[0]
我们可以知道了组合方式:
- P[i] = "("+P[i-j-1]+")"+P[j] (j<i,j=0,1,2,......)
//dp[0] = ""
//dp[i]='('+ dp[k]+')'+dp[i-1-k],k=0..i-i
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector< vector<string> > dp(n+, vector<string>());
dp[].push_back("");
for(int i=; i<=n; ++i){
for(int k=; k<i; ++k){
for(string s1: dp[k]){
for(string s2: dp[i--k])
dp[i].push_back("("+s1+")"+s2);
}
}
}
return dp[n];
}
};
思路2:回溯
假设我能枚举所有的情况,我们考虑合理的括号组合是什么样的:
- 左括号数==右括号数
- 左括号一定要先于右括号
所以我们可以用一个大数组来表示字符串,2个指针leftpare_need,moreleft来表示左右括号,我们递归遍历所有情况,把满足条件的情况加入list就行了
class Solution {
public:
vector<string> result;
vector<string> generateParenthesis(int n) {
helper("", n, );
return result;
}
/* this hepler function insert result strings to "vector<string> result"
When number of '(' less than "n", can append '(';
When number of '(' is more than number of ')', can append ')';
string s : current string;
int leftpare_need : number of '(' that have not put into "string s";
int moreleft : number of '(' minus number of ')' in the "string s";
*/
void helper(string s, int leftpare_need, int moreleft)
{
if(leftpare_need == && moreleft == )
{
result.push_back(s);
return;
}
if(leftpare_need > )
helper(s + "(", leftpare_need - , moreleft+);
if(moreleft > )
helper(s + ")", leftpare_need, moreleft - );
}
};
【LeetCode】【动态规划】Generate Parentheses(括号匹配问题)的更多相关文章
- [LeetCode]22. Generate Parentheses括号生成
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- leetcode 20 Valid Parentheses 括号匹配
Given a string containing just the characters '(', ')', '{', '}', '[' and']', determine if the input ...
- 蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium]
题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...
- LeetCode 20 Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- 【题解】【排列组合】【回溯】【Leetcode】Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- 集训第五周动态规划 J题 括号匹配
Description We give the following inductive definition of a “regular brackets” sequence: the empty s ...
- LeetCode 第20题--括号匹配
1. 题目 2.题目分析与思路 3.代码 1. 题目 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭 ...
- LeetCode 022 Generate Parentheses
题目描述:Generate Parentheses Given n pairs of parentheses, write a function to generate all combination ...
- LeetCode 22 Generate Parentheses(找到所有匹配的括号组合)
题目链接 : https://leetcode.com/problems/generate-parentheses/?tab=Description 给一个整数n,找到所有合法的 () pairs ...
- 【LeetCode】22. Generate Parentheses 括号生成
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:括号, 括号生成,题解,leetcode, 力扣,Pyt ...
随机推荐
- C# Html Agility Pack
using System; using HtmlAgilityPack; using System.IO; using System.Text; using System.Text.RegularEx ...
- macOS10.12部署sonarqube5.6.3
所需安装包已全部上传云盘:https://pan.baidu.com/s/1i5LvOCd 密码:s47e 1. 安装mysql 下载云盘的dmg包,一路默认安装,注意:一定要记住最后一步弹出的默认密 ...
- [LeetCode]Palindrome Number 推断二进制和十进制是否为回文
class Solution { public: bool isPalindrome2(int x) {//二进制 int num=1,len=1,t=x>>1; while(t){ nu ...
- win7-vs2012下安装.net frame work 的过程
第一, vs和.net的对应关系大致如下 vs2010----.net framework 4.0 vs2012----.net framework 4.5 vs2015----.net frame ...
- ifconfig 命令
许多windows非常熟悉ipconfig命令行工具,它被用来获取网络接口配置信息并对此进行修改.Linux系统拥有一个类似的工具,也就是ifconfig(interfaces config).通常需 ...
- Android内容提供者
一个应用中的数据库对别人是不会提供直接的访问的,而是提供接口给别人访问,但是一般应用开发的时候都是去获取别人的数据,而不是自己提供数据. 继承ContentProvider: 在Menifest中注册 ...
- 2018,从AI看安卓生态的变革
AI的发展与影响 与传统技术不同的是,AI技术算法清晰,优化目标明确,基础技术成熟,使得一众中小创企也看到了市场的机会.2017年中国企业动作频频,在自动驾驶,智能安防,智慧城市等领域都取得了不俗的成 ...
- 好文章收藏--五分钟理解一致性哈希算法(consistent hashing)
一致性哈希算法在1997年由麻省理工学院提出的一种分布式哈希(DHT)实现算法,设计目标是为了解决因特网中的热点(Hot spot)问题,初衷和CARP十分类似.一致性哈希修正了CARP使用的简 单哈 ...
- struts2中配置文件加载的顺序是什么?
struts2的StrutsPrepareAndExecuteFilter拦截器中对Dispatcher进行了初始化 在Dispatcher类的init方法中定义了配置文件的加载顺序(下面是源码) p ...
- git 撤销已经push到远端的代码
其实是没有直接让远端代码回复到某次的指令,实现撤销push的思路如下: 1.先让代码恢复到想要恢复的前一次提交记录 2.重新提交代码,覆盖端上的代码,就相当于撤销了push 的提交 实现方式如下: 1 ...