22. Generate Parentheses--递归法
来源:互联网 发布:淘宝店铺托管费用 编辑:程序博客网 时间:2024/06/05 21:30
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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
一般来说是用递归的方法,因为可以归结为子问题去操作。在每次递归函数中记录左括号和右括号的剩余数量,然后有两种选择,一个是放一个左括号,另一种是放一个右括号。需要特别注意的是剩余的右括号不能比左括号少,左括号右括号数量都要大于0。
如果只是要输出结果有多少组,那么直接用卡特兰数的公式就可以。
vector<string> generateParenthesis(int n) { vector<string> res; addpair(res,"",n,0); //右括号的数目记录为n,左括号的记录为m,一开始设置右括号数目为n,左括号的数目为0,从而很好的控制了任意时刻左括号的数目要大于右括号的数目 return res; } void addpair(vector<string> &res,string str,int n,int m){ if(n == 0 && m == 0){ res.push_back(str); return; } if(m > 0){addpair(res,str + ")",n, m - 1);} if(n > 0){addpair(res,str + "(",n - 1, m + 1);} }
更好理解的递归过程
vector<string> generateParenthesis(int n) { vector<string> res; addpair(res,"",n,n); return res; } void addpair(vector<string> &res,string str,int left,int right){ if(right < left) return; //注意此处的left和right代表左括号和右括号的剩余数,递归的过程中一定要保证右括号的剩余数大于左括号的剩余数 if(left == 0 && right == 0){ res.push_back(str); } if(left > 0){addpair(res,str + "(",left - 1, right );} if(right > 0){addpair(res,str + ")",left, right - 1);} }
0 1
- 22. Generate Parentheses--递归法
- 递归22. Generate Parentheses
- leetcode 22. Generate Parentheses 递归
- leetcode 22. Generate Parentheses-回溯|递归
- leetcode 22. Generate Parentheses (暴力递归)
- leetcode---Generate Parentheses---递归
- [leetcode] 22 Generate Parentheses(递归)
- LeetCode Generate Parentheses递归方法
- Leetcode-Generate Parentheses(递归)
- 22.leetcode Generate Parentheses(medium)[函数递归遍历]
- leetcode 22. Generate Parentheses 巧妙的递归形式
- LeetCode OJ-22.Generate Parentheses(回溯法)
- [LeetCode]22.Generate Parentheses
- LeetCode --- 22. Generate Parentheses
- LeetCode 22.Generate Parentheses
- [Leetcode] 22. Generate Parentheses
- 【LeetCode】22.Generate Parentheses
- 22. Generate Parentheses
- listview属性
- Spring定时任务的几种实现
- 为什么做java的web开发我们会使用struts2,springMVC和spring这样的框架?
- opencv中的SVM图像分类(一)
- Android Studio 解决Error occurred during initalization of VM
- 22. Generate Parentheses--递归法
- PAT A1003
- 层级遍历二叉树
- HTTP请求错误400、401、402、403、404、405、406、407、412、414、500、501、502解析
- 2017年伊始,你需要尝试的25个Android第三方库
- Spring与Quartz实现动态更新定时任务
- mariadb主从复制及互为主从配置过程
- PFN最新的目标检测算法
- InfoGAN介绍