[LintCode] Generate Parentheses 生成括号
2016-07-18 23:39
357 查看
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Have you met this question in a real interview?
Example
Given
LeetCode上的原题,请参见我之前的博客Generate Parentheses。
解法一:
解法二:
Have you met this question in a real interview?
Example
Given
n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
LeetCode上的原题,请参见我之前的博客Generate Parentheses。
解法一:
class Solution { public: /** * @param n n pairs * @return All combinations of well-formed parentheses */ vector<string> generateParenthesis(int n) { if (n == 0) return {}; vector<string> res; helper(n, n, "", res); return res; } void helper(int left, int right, string out, vector<string>& res) { if (left < 0 || right < 0 || left > right) return; if (left == 0 && right == 0) { res.push_back(out); return; } helper(left - 1, right, out + "(", res); helper(left, right - 1, out + ")", res); } };
解法二:
class Solution { public: /** * @param n n pairs * @return All combinations of well-formed parentheses */ vector<string> generateParenthesis(int n) { set<string> res; if (n == 0) { res.insert(""); } else { vector<string> pre = generateParenthesis(n - 1); for (auto a : pre) { for (int i = 0; i < a.size(); ++i) { if (a[i] == '(') { a.insert(a.begin() + i + 1, '('); a.insert(a.begin() + i + 2, ')'); res.insert(a); a.erase(a.begin() + i + 1, a.begin() + i + 3); } } res.insert("()" + a); } } return vector<string>(res.begin(), res.end()); } };
相关文章推荐
- CCNP笔记——MST上
- 大数相加+斐波那契数列(1)
- LINUX-内核-中断分析-中断向量表(1)-x86
- 网络协程编程
- strcat()和strncat()函数的实现
- WebRTC Data Channels RFC
- 利用Qt的QDateTimeEdit设置起始时间(即开始时间大于结束时间)
- Android自定义ProgressDialog进度等待框
- NYOJ33--蛇形填数
- 7 rules of Effortless English System Secret (Ⅶ)
- HDU-4339 Query(树状数组+二分)
- Leetcode 100 : same Tree
- vim
- InstallShield Limited Edition for Visual Studio 2013 图文教程(教你如何打包.NET程序)
- PAT乙级.1026. 程序运行时间(15)
- Python爬虫常用模块,BeautifulSoup笔记
- [置顶] 指针与数组(二)——字符串认知
- 【LeetCode】12. Integer to Roman
- 深度学习实战——caffe windows 下训练自己的网络模型
- POJ-2104 K-th Number