从leetcode—Generate Parentheses看卡特兰数
来源:互联网 发布:棉花数据 编辑:程序博客网 时间:2024/05/01 15:27
<span style="line-height: 27.7894744873047px; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">Generate Parentheses</span>
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Subscribe to see which companies asked this question
仔细思考这个问题,打印所有正确的n对括号序列,所有合法序列在打印的时候由于括号是封闭的所以当你打印一个右括号的时候,前面必须有一个左括号与之对应,用更简单的方法表示if(left>right){you can print right ;right++}当然left《=n。
这和买票找零钱问题(一半人拿5元,一半人拿10元,票价如何排列可以顺利的售票),
站队问题(站两排,每排必须从高到矮,二排必须比对应的一排人高)。
都属于catalan(卡特兰数总感觉用英文高大上一点)问题:
Catalan数的定义令h(1)=1,Catalan数满足递归式:h(n) = h(1)*h(n-1) + h(2)*h(n-2) + ... + h(n-1)h(1),n>=2该递推关系的解为:h(n) = C(2n-2,n-1)/n,n=1,2,3,...(其中C(2n-2,n-1)表示2n-2个中取n-1个的组合数)
现在回到这个问题上,他要求我们打印所有序列而不是简单的算可能性。若果把想成它想成一个出度为2的有向图,可以用深度搜索打印序列。代码如下:
class Solution {public:void generate(int re_left,int re_right,string s,vector<string> &answer){if(re_left==0 && re_right==0){answer.push_back(s);}if(re_left>0){generate(re_left-1,re_right,s+'(',answer);}if(re_right>0 && re_right > re_left){generate(re_left,re_right-1,s+')',answer);}} vector<string> generateParenthesis(int n) { vector<string> answer;string s ="";generate(n,n,s,answer);return answer; }};
- 从leetcode—Generate Parentheses看卡特兰数
- Generate Parentheses(卡特兰数)
- [C++]LeetCode: 84 Generate Parentheses (卡特兰数)
- leetcode——backtracking[1] Generate Parentheses ,Catalan数——卡特兰数
- LeetCode 22 Generate Parentheses 卡特兰数问题,有待进一步学习
- 卡特兰数——generate-parentheses 打印成对的括号
- 【LeetCode从零单刷】Generate Parentheses
- Catalan数——卡特兰数
- Catalan数——卡特兰数
- Catalan数——卡特兰数
- Catalan数——卡特兰数
- Catalan数——卡特兰数
- Catalan数——卡特兰数
- Catalan数——卡特兰数
- Catalan数——卡特兰数
- 卡特兰数——Catalan数
- Catalan数—卡特兰数
- 卡特兰数,高精度卡特兰数
- jQuery+ajax+json+php+MySQL
- 获取进程名的两种方法
- 硬链接的创建及删除
- meanjs中的服务
- django 项目中使用多数据库 multiple databases - 真实的活
- 从leetcode—Generate Parentheses看卡特兰数
- 【Mybatis进阶】-- mybatis架构
- Java Runtime.exec()的使用
- Swift - 使用CoreLocation实现定位(经纬度、海拔、速度、距离等)
- SPEC2000 测试
- 科研数据集
- swift表格(UITableView)介绍与基础实现
- python 获取网络时间及修改本地时间
- set