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)的更多相关文章

  1. 【LeetCode】22. Generate Parentheses (I thought I know Python...)

    I thought I know Python... Actually , I know nothing... 这个题真想让人背下来啊,每一句都很帅!!! Given n pairs of paren ...

  2. 【LeetCode】22. Generate Parentheses 括号生成

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:括号, 括号生成,题解,leetcode, 力扣,Pyt ...

  3. 【leetcode】22. Generate Parentheses

    题目描述: Given n pairs of parentheses, write a function to generate all combinations of well-formed par ...

  4. 【一天一道LeetCode】#22. Generate Parentheses

    一天一道LeetCode (一)题目 Given n pairs of parentheses, write a function to generate all combinations of we ...

  5. [Leetcode][Python]22: Generate Parentheses

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 22: Generate Parentheseshttps://oj.leet ...

  6. LeetCode OJ 22. Generate Parentheses

    题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...

  7. 【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 ...

  8. 【LeetCode】90. Subsets II (2 solutions)

    Subsets II Given a collection of integers that might contain duplicates, S, return all possible subs ...

  9. 【LeetCode】478. Generate Random Point in a Circle 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/generate ...

随机推荐

  1. 物联网(IoT)的11大云平台:AWS、Azure、谷歌云、Oracle、

    物联网(IoT)的11大云平台:AWS.Azure.谷歌云.Oracle. 2018-11-06 14:02 云技术 关键词:物联网AzureGoogleSalesforce云计算 导读:现在,我们将 ...

  2. Matlab制作个人主页

     Matlab代码编辑器具有代码发布功能,如下图,当编辑好代码后,点击Publish按钮可以发布html网页格式的代码使用说明.       从上面的图中可以看到,发布功能可以控制字体(黑体.斜体.等 ...

  3. 学习笔记:A*算法

    简易地图 如图所示简易地图, 其中绿色方块的是起点 (用 A 表示), 中间蓝色的是障碍物, 红色的方块 (用 B 表示) 是目的地. 为了可以用一个二维数组来表示地图, 我们将地图划分成一个个的小方 ...

  4. Objective-C:MRC手动释放对象内存举例(引用计数器)

    手机内存下的类的设计练习: 设计Book类, 1.三个成员变量:    title(书名)author(作者).price(价格) 2.不使用@property,自己完成存取方法(set方法,get方 ...

  5. Objective-C:分类(Category、extension)

    分类(Category .Extension) (一)分类的划分     (2) 1.(命名的类别)类别Category:只能添加新的方法,不能添加新变量.           2.(未命名的类别)类 ...

  6. 第十四章 springboot + profile(不同环境读取不同配置)

    具体做法: 不同环境的配置设置一个配置文件,例如:dev环境下的配置配置在application-dev.properties中:prod环境下的配置配置在application-prod.prope ...

  7. crtmpserver实现防盗流和流推送验证

    Protecting your streams from webpage copy&paste flash code, listing or recording 保护流,防止在页面上被复制&a ...

  8. 5种调优Java NIO和NIO.2的方式

    Java NIO(New Input/Output)——新的输入/输出API包——是2002年引入到J2SE 1.4里的.Java NIO的目标是提高Java平台上的I/O密集型任务的性能.过了十年, ...

  9. C#.NET常见问题(FAQ)-浮点数如何四舍五入

    使用Math.Round方法即可实现保留指定的小数点后面位数,这种方法返回的还是double类型,而ToString方法并没有做实际转换   更多教学视频和资料下载,欢迎关注以下信息: 我的优酷空间: ...

  10. [置顶] macbook 深度休眠和待机

    开发用了macbook pro, 10.8.3, 因为用windows的习惯,一直比较习惯不关机,直接休眠,不是待机standby,今天找到了一个工具,可以实现,亲测通过. 下载:https://gi ...