博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
22.Generate Parentheses (String; Back-Track)
阅读量:4705 次
发布时间:2019-06-10

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

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:

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

思路:两个递归函数,互相调用

class Solution {public:    vector
generateParenthesis(int n) { if(n==0) return ret; dfsLeft("",0,0,n); return ret; } void dfsLeft(string s, int depthLeft, int depthRight, int n){ //add one left parenthesis if(depthLeft >= n){ //end left return; } else{ s += '('; depthLeft++; dfsRight(s,depthLeft, depthRight, n); dfsLeft(s,depthLeft, depthRight, n); } } void dfsRight(string s, int depthLeft, int depthRight, int n){ //add one right parenthesis if(depthRight >= n){ //end all ret.push_back(s); } else if(depthRight >= depthLeft){ //end right return; } else{ s += ')'; depthRight++; dfsLeft(s,depthLeft, depthRight, n); dfsRight(s,depthLeft, depthRight, n); } }private: int len; vector
ret;};

更简洁的写法:

class Solution {public:    vector
generateParenthesis(int n) { if(n == 0) return ret; len = n*2; dfsLeft(n, 0, ""); return ret; } void dfsRight(int lNum, int rNum, string str){
//add right parenthese while(rNum){ str += ')'; dfsLeft(lNum, --rNum, str); } if(str.length() == len){ ret.push_back(str); } } void dfsLeft(int lNum, int rNum, string str){
//add left parenthese while(lNum){ str += '('; dfsRight(--lNum, ++rNum, str); } }private: int len; vector
ret;};

 

转载于:https://www.cnblogs.com/qionglouyuyu/p/4705551.html

你可能感兴趣的文章
cnblog!i'm coming!
查看>>
使用点符号代替溢出的文本
查看>>
fatal: remote origin already exists.
查看>>
LeetCode 242. Valid Anagram
查看>>
JSP表单提交乱码
查看>>
如何适应现代雇佣关系
查看>>
团队项目(第五周)
查看>>
SQL 优化经验总结34条
查看>>
开源 视频会议 收藏
查看>>
核心J2EE模式 - 截取过滤器
查看>>
.net开源CMS
查看>>
JdbcTemplate
查看>>
第一次使用maven记录
查看>>
SharePoint服务器端对象模型 之 使用CAML进展数据查询
查看>>
Building Tablet PC Applications ROB JARRETT
查看>>
Adobe® Reader®.插件开发
查看>>
【POJ 3461】Oulipo
查看>>
Alpha 冲刺 (5/10)
查看>>
使用Siege进行WEB压力测试
查看>>
斑马为什么有条纹?
查看>>