【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 ...
随机推荐
- JAVA常见算法题(三十五)
判断一个整数能被几个9整除. public static void main(String[] args) { f(729); f(730); } public static void f(int n ...
- strcat实现
//将源字符串加const,表明其为输入参数 char*strcat(char*strDest,constchar*strSrc) { //后文returnaddress,故不能放在assert断言之 ...
- 【BZOJ】【3240】【NOI2013】矩阵游戏
十进制快速幂+矩阵乘法+常数优化 听说这题还可以强行算出来递推式……然后乘乘除除算出来…… 然而蒟蒻选择了一个比较暴力的做法= = 我们发现这个递推的过程是线性的,所以可以用矩阵乘法来表示,$x=a* ...
- iOS:UITableViewCell自定义单元格
UITableViewCell:自定义的单元格,可以在xib中创建单元格,也可以在storyBorad中创建单元格.有四种创建方式 <1>在storyBorad中创建的单元格,它是静态的单 ...
- iOS:转载:UIControl的使用
主要功能: UIContol(控件是所有控件的基类 如:(UIButton)按钮主要用于与用户交互,通常情况下我们不会直接使用UIControl,而是子类化它. 常用属性: BOOL enabled ...
- Kmeans算法原理极其opencv实现(转帖)
原帖地址:http://blog.csdn.net/qll125596718/article/details/8243404 1.基本Kmeans算法[1] 选择K个点作为初始质心 repeat ...
- 第六章 企业项目开发--cookie
注:本章代码基于<第五章 企业项目开发--mybatis注解与xml并用>的代码,链接如下: http://www.cnblogs.com/java-zhao/p/5120792.html ...
- hdu 4445 Crazy Tank
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> ...
- 【Hadoop】Combiner的本质是迷你的reducer,不能随意使用
问题提出: 众所周知,Hadoop框架使用Mapper将数据处理成一个<key,value>键值对,再网络节点间对其进行整理(shuffle),然后使用Reducer处理数据并进行最终输出 ...
- [Backbone] First Application!!!!
Important things to remember: 1. Usually, we create Collection, CollectionViews, Model, View. Collec ...