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:

"((()))", "(()())", "(())()", "()(())", "()()()"

思路:产生所有合理的括号配对

我自己用的回溯法,遍历所有压入第k个')'时前面'('个数

class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
if(n == )
return ans; vector<vector<char>> S(n); //放入第k个右括号时,已经放入的左括号数目
int k = ;
for(int i = k + ; i <= n; i++)
{
S[k].push_back(i);
}
string X;
while(k >= )
{
while(!S[k].empty())
{
int numOfLeftP = getNumOfLeft(X); //还没有放入的左括号数目
while(numOfLeftP < S[k].back()) //如果X中"("少于需要的,压入"("
{
X.append("(");
numOfLeftP++;
}
while(numOfLeftP > S[k].back()) //如果X中"("多于需要的,弹出
{
char back = X.back();
X.pop_back();
if(back == '(')
{
numOfLeftP--;
}
}
X.append(")"); //压入新的")"
int back = S[k].back();
S[k].pop_back(); if(k < n - )
{
k++;
int num = max(back, k + ); //可以选择的已有左括号数必须大于当前已有的 小于等于n
for(int i = num; i <= n; i++)
{
S[k].push_back(i);
}
}
else
{
ans.push_back(X);
}
}
k--;
}
return ans;
} int getNumOfLeft(string X)
{
int position=;
int i=;
while((position=X.find_first_of("(",position))!=string::npos)
{
position++;
i++;
}
return i;
} };

我的思路很繁琐,中间要做各种判断,看下大神的。

产生长度为 2*n的括号, 但是不能随便产生

设len是当前的字符串长度, v是当前完整配对的括号对数

如果 len - v < n 还可以放入'('

如果 2 * v < len 还可以放入')'

当长度符合条件就压入答案,只有这时stack长度才会减小,其他长度下会压入新值。

vector<string> generateParenthesis2(int n) {
vector<string> ans;
vector<string> stack;
vector<int> validationStack;
stack.push_back("(");
validationStack.push_back();
while(stack.size() != )
{
string s = stack.back();
stack.pop_back();
int v = validationStack.back();
validationStack.pop_back();
if(s.length() == * n)
{
ans.push_back(s);
continue;
}
if(s.length() - v < n)
{
stack.push_back(s.append("("));
validationStack.push_back(v);
s.pop_back();
}
if( * v < s.length())
{
stack.push_back(s.append(")"));
validationStack.push_back(v + );
s.pop_back();
}
}
return ans; }

【leetcode】 Generate Parentheses (middle)☆的更多相关文章

  1. 【LeetCode】Generate Parentheses 解题报告

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

  2. 【题解】【排列组合】【回溯】【Leetcode】Generate Parentheses

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

  3. 【leetcode】Generate Parentheses

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

  4. 【Leetcode】【Medium】Generate Parentheses

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

  5. 【LeetCode】【动态规划】Generate Parentheses(括号匹配问题)

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

  6. 【leetcode】Sort List (middle)

    Sort a linked list in O(n log n) time using constant space complexity. 思路: 用归并排序.设输入链表为S,则先将其拆分为前半部分 ...

  7. 【LeetCode】Valid Parentheses(有效的括号)

    这道题是LeetCode里的第20道题. 题目要求: 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭 ...

  8. 【leetcode】Valid Parentheses

    题目简述: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if th ...

  9. 【leetcode】Subsets II (middle) ☆

    Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: ...

随机推荐

  1. PlayMaker 学习笔记

    1.v1.7.8.3版本无法使用全局变量,原因是Assets\Plugins\PlayMaker下的Resources文件夹变成中文了,无法创建全局变量文件,手动创建一个Resources文件夹即可

  2. HDOJ 4747 Mex

    非常好的线段树题....此题必定会火..... Mex Time Limit: 15000/5000 MS (Java/Others)    Memory Limit: 65535/65535 K ( ...

  3. UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence

    混淆了 python2 里边的 str 和 unicode 数据类型. 1. 对需要 str->unicode 的代码,可以在前边写上 import sys reload(sys) sys.se ...

  4. Knockout.Js案例三单页面应用程序

    <ul data-bind="foreach: folders">      <li data-bind="text: $data">& ...

  5. Mac OS X 11以上系统的Rootless机制问题

    由于项目紧,系统一直停留在10版本,最近清闲之后,第一件事就是升级了系统,到11El Capitan版本. 本来想着随便升级了,可能有好玩的东东,结果好玩的木有看见,项目开发环境崩溃了,何其衰耶? 废 ...

  6. 2015年最有价值的30个响应式WORDPRESS主题

    http://www.chinaz.com/design/2015/0521/408204.shtml 必须承认,Wordpress依然是目前最流行.最易用的内容管理系统,合理地使用Wordpress ...

  7. Python验证Url地址的正则表达式

    如下是django中做url验证的正则表达式: regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z ...

  8. word20161203

    B-channel / B 信道 B-ISDN, broadband integrated services digital network / 广播综合业务数字网络 backbone router  ...

  9. servlet部分知识总结

    1.解决中文显示乱码问题: 对于servlet :servlet里面加入代码response.setContentType("text/html;chartset=utf-8"); ...

  10. JSON代码格式化 进行查询筛选

    JSON是前端编程经常用到的格式,对于PHP或者Python,解析JSON都不是什么大事,尤其是PHP的json_encode和json_decode,干的相当的漂亮.Linux下也有处理处理JSON ...