[Leetcode] 22. Generate Parentheses 解题报告
来源:互联网 发布:jquery 对象添加数据 编辑:程序博客网 时间:2024/06/02 02:40
题目:
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<string> generateParenthesis(int n) { vector<string> ret; if(n == 0) return ret; string line; generateParenthesis(ret, line, 0, 0, n); return ret; }private: void generateParenthesis(vector<string>& ret, string& line, int left, int right, int n) { if(left > n) return; if(left == n && right == n) { ret.push_back(line); return; } if(left == right) // we can only add '(' { line += '('; generateParenthesis(ret, line, left + 1, right, n); line.pop_back(); } else if(left > right) // we can add both '(' and ')' { line += '('; generateParenthesis(ret, line, left + 1, right, n); line.pop_back(); line += ')'; generateParenthesis(ret, line, left, right + 1, n); line.pop_back(); } }};
0 0
- [leetcode] 22. Generate Parentheses 解题报告
- LeetCode 22. Generate Parentheses 解题报告
- [Leetcode] 22. Generate Parentheses 解题报告
- leetcode解题报告22. Generate Parentheses
- [LeetCode]Generate Parentheses, 解题报告
- 【LeetCode】Generate Parentheses 解题报告
- LeetCode解题报告--Generate Parentheses
- [LeetCode] Generate Parentheses 解题报告
- [LeetCode] Generate Parentheses 解题报告
- Generate Parentheses LeetCode解题报告
- Leetcode #22 Generate Parentheses 创建括号 解题报告
- [leetcode javascript解题]Generate Parentheses
- Leetcode Generate Parentheses 解题思路
- Generate Parentheses——解题报告
- [LeetCode]22.Generate Parentheses
- LeetCode --- 22. Generate Parentheses
- LeetCode 22.Generate Parentheses
- [Leetcode] 22. Generate Parentheses
- Web应用场景下缓存参数的数学模型
- 关于Java代码中数据库操作的感悟.
- 由微服务架构带来的四大质量挑战
- MongoDB与关系型数据库的区别
- 稳扎稳打JavaScript(二)——图解对象内存模型
- [Leetcode] 22. Generate Parentheses 解题报告
- new一个二维数组
- 脉冲星测时软件TEMPO2安装
- IP分片浅析
- LearnOpenGL 1.4 着色器
- 在Editplus中配置java的(带包)编译(javac)和运行(java)的方法
- java
- nginx handler模块
- FastStone 7.7注册码有效