博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【题解】【排列组合】【回溯】【Leetcode】Generate Parentheses
阅读量:7084 次
发布时间:2019-06-28

本文共 1147 字,大约阅读时间需要 3 分钟。

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

思路:

有关Parentheses的题目也是比较常见的,除了还有,

回溯用递归写是性价比最高的,基本思想就是从前往后填字符保证'('的个数不能比')'少,且'('的个数不能比n多

代码:

1 void generateAtDepth(vector
&Parentheses, string &p, int lefts, int rights, int depth, int n){ 2 if(depth == 2*n-1){ 3 p[depth] = ')'; 4 Parentheses.push_back(p); 5 return;//返回值为void的函数不能忘了return啊! 6 } 7 if(lefts < n){
//注意不能出现((() 8 p[depth] = '('; 9 generateAtDepth(Parentheses, p, lefts+1, rights, depth+1, n);10 }11 if(lefts > rights){12 p[depth] = ')';13 generateAtDepth(Parentheses, p, lefts, rights+1, depth+1, n);14 }15 }16 vector
generateParenthesis(int n) {17 vector
Parentheses;18 if(n < 1) return Parentheses;19 string p(2*n, '*');//一定要指定初始化字符20 generateAtDepth(Parentheses, p, 0, 0, 0, n);21 return Parentheses;22 }

 

 

转载于:https://www.cnblogs.com/wei-li/p/GenerateParentheses.html

你可能感兴趣的文章
linux中日志的管理
查看>>
在linux下查看内核版本、gcc版本、操作系统多少位等参数
查看>>
鹅厂奋战历程简录
查看>>
从零开始成为一名开源程序员,其实只需要九步!
查看>>
1周2次课
查看>>
OSI模型和TCP/IP协议栈
查看>>
基于centos6.x环境下GRE隧道的搭建及分析
查看>>
AssetBundle 打包资源
查看>>
HSRP热备份
查看>>
js判断变量数据类型
查看>>
通过思科模拟器CISCO PACKET TRACER学习网络8——RIP路由
查看>>
linux下安装oracle11g实例
查看>>
Centos7搭建OpenNebula云平台
查看>>
Shell流程控制之if语句
查看>>
快过高铁!构建云分布式应用还能这样操作?!
查看>>
ftp服务器的搭建于三种访问途径
查看>>
字节流与字符流的区别及相互转换
查看>>
教你将PDF文件旋转的方法
查看>>
初识 Knative: 跨平台的 Serverless 编排框架
查看>>
字符串匹配
查看>>