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. poj 3041 Asteroids 题解

    Asteroids Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 20686   Accepted: 11239 Descr ...

  2. 原创BULLET物理的DEMO

    原创BULLET物理的DEMO 按空格和0,1,2,3,4,5,6会发射不同的刚体. 具体的使用说明: 鼠标右键按下并拖动         旋转视角WSAD                       ...

  3. [转]局域网共享一键修复 18.5.8 https://zhuanlan.zhihu.com/p/24178142

    @echo offcolor 2fmode con cols=50 lines=30title OKShare [制作:wnsdt]ver | findstr "6.">nu ...

  4. Javascript执行效率总结

    Javascript是一门非常灵活的语言,我们可以随心所欲的书写各种风格的代码,不同风格的代码也必然也会导致执行效率的差异,开发过程中零零散散地接触到许多提高代码性能的方法,整理一下平时比较常见并且容 ...

  5. Cognos创建Oracle数据源错误以及客户端生成加密信息错误

    报加密错误,先删除 signkeypair csk encrytkeypair三个目录错误一: 创建Oracle数据源错误,在cognos connection中创建oracle的数据源,一直测试不成 ...

  6. c语言訪问excel

    直接通过格式化读取文件就可实现,见附件

  7. Android控件之HorizontalScrollView 去掉滚动栏

    在默认情况下.HorizontalScrollView控件里面的内容在滚动的情况下,会出现滚动栏,为了去掉滚动栏.仅仅须要在<HorizontalScrollView/>里面加一句    ...

  8. C#.NET常见问题(FAQ)-interface接口如何理解

    个人把interface理解为一种比较特殊的判断技巧,不是常规的变量类型比如判断字符串,判断数组,而是判断类的实例是否拥有某些属性或者方法(比如有十个女的穿一样的衣服,头上盖住,让新郎去猜哪一个是他的 ...

  9. Strange Addition

    http://codeforces.com/problemset/problem/305/A 这题就是意思没看懂,一开始以为只要个位数只要一个为0就能相加,没想到到CF里面提交第三组就过不了,才发现是 ...

  10. Android 逆向project 实践篇

    Android逆向project 实践篇 上篇给大家介绍的是基础+小Demo实践. 假设没有看过的同学能够进去看看.(逆向project 初篇) 本篇主要给大家介绍怎样反编译后改动源代码, 并打包执行 ...