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. 基尼系数(Gini coefficient),洛伦茨系数

    20世纪初意大利经济学家基尼,于1922年提出的定量测定收入分配差异程度的指标.它是根据洛伦茨曲线找出了判断分配平等程度的指标(如下图). 设实际收入分配曲线和收入分配绝对平等曲线之间的面积为A,实际 ...

  2. Transform导入数据源TR1008错误

    cognos在建设初期开发者们都常常遇到的一个问题,在这里做一下小小的总结. iqd作为Transform的数据源导入数据的时候遭遇TR1008错误 注意: 从报错的内容可以看出transform不能 ...

  3. 查看sedna创建的数据库和集合,文档之类

    在sedna的安装文件夹下.看一下cfg文件夹: <pre name="code" class="plain">[xuzhina@localhost ...

  4. [Javascript] Create Objects

    var vehicle1 = {type: "Motorboat", capacity: 6, storedAt: "Ammunition Depot"}; v ...

  5. C#.NET常见问题(FAQ)-控制台程序如何输出Messagebox

    1 添加如下引用   2 添加引用和Messagebox的代码.   3 测试可行     更多教学视频和资料下载,欢迎关注以下信息: 我的优酷空间: http://i.youku.com/aceta ...

  6. Android IO存储总结

    1 前言  android设备的存储特点:  分内存和SD卡两种存储设备,且android设备存储空间小,且系统碎片化等情况.     SD卡:老版本的android设备 不存在内置SD        ...

  7. Failed to fetch URL https://dl-ssl.google.com/android/repository/repository-6.xml, reason: Connection to https://dl-ssl.google.com refused

    修改hosts文件.文件在C:\WINDOWS\system32\drivers\etc目录下,Linux用户打开/etc/hosts文件.用记事本打开文件后添加以下内容. #Google主页203. ...

  8. linux 目录结构(转)

    原文:http://www.centoscn.com/CentOS/2014/1222/4347.html linux 目录结构 /: 根目录,一般根目录下只存放目录,不要存放文件,/etc./bin ...

  9. Java从零开始学十七(简单工厂)

    简单工厂的实现 实现一个计算器:要求输入2个数,和运算符,得到结果 Operation类 package com.pb.demo1; public class Operation { private ...

  10. 算法笔记_001:斐波那契数的多种解法(Java)

    本篇文章解决的问题来源于算法设计与分析课程的课堂作业,主要是运用多种方法来计算斐波那契数.具体问题及解法如下: 一.问题1: 问题描述:利用迭代算法寻找不超过编程环境能够支持的最大整数的斐波那契数是第 ...