【LeetCode】22. Generate Parentheses (2 solutions)
Generate Parentheses
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
解法一:递归
借助栈,'('、')'构成一对分别进出栈。最后栈为空,则输入括号构成的字符串是合法的。
注意:调用top()前先check一下栈是否为空
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
if(n == )
return result;
//first must be '('
string cur = "(";
stack<char> s;
s.push('(');
Helper(result, cur, s, *n-);
return result;
}
void Helper(vector<string>& result, string cur, stack<char> s, int num)
{
if(num == )
{//must be ')'
if(s.top() == '(' && s.size() == )
{//all matched
cur += ')';
result.push_back(cur);
}
}
else
{
//'(' always push
string str1 = cur;
str1 += '(';
s.push('(');
Helper(result, str1, s, num-);
s.pop();
//')'
if(!s.empty())
{//prune. never begin with ')'
string str2 = cur;
str2 += ')';
if(s.top() == '(')
s.pop(); //check empty() before access top()
else
s.push(')');
Helper(result, str2, s, num-);
}
}
}
};

解法二:递归
稍作分析可知,栈是不必要的,只要记录字符串中有几个'(',记为count。
每进入一个'(', count ++. 每匹配一对括号, count--。
最终全部匹配,需要count==0
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ret;
string cur = "(";
gen(ret, cur, *n-, );
return ret;
}
void gen(vector<string>& ret, string cur, int k, int count)
{
if(k == )
{//last paretheses
if(count == )
{//one unmatched '('
cur += ')';
ret.push_back(cur);
}
}
else
{
if(count >= )
{//either '(' or ')'
//'('
count ++;
if(count <= k-)
{//otherwise, all ')'s are still not enough
cur += '(';
gen(ret, cur, k-, count);
cur.erase(cur.end()-);
}
count --;
//')'
if(count > )
{
count --;
cur += ')';
gen(ret, cur, k-, count);
cur.erase(cur.end()-);
count ++;
}
}
}
}
};

【LeetCode】22. Generate Parentheses (2 solutions)的更多相关文章
- 【LeetCode】22. Generate Parentheses (I thought I know Python...)
I thought I know Python... Actually , I know nothing... 这个题真想让人背下来啊,每一句都很帅!!! Given n pairs of paren ...
- 【LeetCode】22. Generate Parentheses 括号生成
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:括号, 括号生成,题解,leetcode, 力扣,Pyt ...
- 【leetcode】22. Generate Parentheses
题目描述: Given n pairs of parentheses, write a function to generate all combinations of well-formed par ...
- 【一天一道LeetCode】#22. Generate Parentheses
一天一道LeetCode (一)题目 Given n pairs of parentheses, write a function to generate all combinations of we ...
- [Leetcode][Python]22: Generate Parentheses
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 22: Generate Parentheseshttps://oj.leet ...
- LeetCode OJ 22. Generate Parentheses
题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...
- 【LeetCode】75. Sort Colors (3 solutions)
Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects of t ...
- 【LeetCode】90. Subsets II (2 solutions)
Subsets II Given a collection of integers that might contain duplicates, S, return all possible subs ...
- 【LeetCode】478. Generate Random Point in a Circle 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/generate ...
随机推荐
- OpenCV学习(28) 轮廓
OpenCV中可以方便的在一副图像中检测到轮廓,并把这些轮廓画出来.主要用到两个函数:一个是findContours( img, contours0, hierarchy, RETR_TREE, CH ...
- LeetCode 84. Largest Rectangle in Histogram 单调栈应用
LeetCode 84. Largest Rectangle in Histogram 单调栈应用 leetcode+ 循环数组,求右边第一个大的数字 求一个数组中右边第一个比他大的数(单调栈 Lee ...
- JS中应用正则表达式转换大小写
JS中应用正则表达式转换大小写,代码很简单,看代码: 以下首字母大写,其它字母小写 <script type="text/javascript"> function r ...
- GoLang中flag标签使用
正如其他语言一样,在 linux 系统上通过传入不同的参数来使得代码执行不同逻辑实现不同功能,这样的优点就是执行想要的既定逻辑而不需要修改代码重新编译与打包.在 Golang 语言中也为我们提供了相应 ...
- 如何将数据转换libsvm格式文件
原文:http://blog.sina.com.cn/s/blog_5c2f929b0100qse8.html 有三种工具可用1.网上有一个xls文FormatDataLibsvm.xls具有宏命令, ...
- 老三星手机i9001刷机记录
家里的老的三星i9001,准备给我妈用,打算刷机,但又实在头疼那些复杂的刷机技术,昨天研究了一下,用比较简单的方法完成刷机,记录如下: 用卡刷比较简单,线刷不考虑 进入恢复模式的方法:1.电源+音量加 ...
- 运维-JVM监控之内存泄漏
转载:https://blog.csdn.net/zdx_csdn/article/details/71214219 jmap -heap pid查看进程堆内存使用情况,包括使用的GC算法.堆配置参数 ...
- 程序员们必备的10款免费jquery插件
本周带来10款免费的jquery插件.如果你也有好的作品,欢迎分享到社区中来,在得到帮助的同时,也能与更多人分享来自你的作品. jQuery导航菜单置顶插件 - stickyUp . 在线演示 sti ...
- eclipse在search的时候,通过search打开的页面会覆盖之前打开的页面
eclipse在search的时候,通过search打开的页面会覆盖之前打开的页面,如果不想覆盖的话,可以这么设置: Window->Preferences->General->Se ...
- Android 的一些提示框
1.在测试时,如何实现一个提示 可以使用 Toast.makeText(this, "这是一个提示", Toast.LENGTH_SHORT).show(); //从资源文件str ...