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. 【翻译】Tomcat 6.0 安装与启动

    本篇来自Tomcat6官方文档:运行手册running.txt 有很多以前都没注意的问题,这里正好学习下. 系列文章来自:<Tomcat官方文档翻译> Tomcat的安装 1 确认本机是否 ...

  2. firstchild.data与childNodes[0].nodeValue意思(转)

    x.firstchild.data:获取元素第一个子节点的数据: x.childNodes[0]::获取元素第一个子节点; x.childNodes[0].nodeValue.:也是获取元素第一个子节 ...

  3. JSP中根据不同的条件显示不一样的格式

    在做项目中遇到这样的场景: 当查询到记录时,需要将记录的字段作为下拉列表,让用户选择使用,即显示的是下拉列表. 当没有查询到记录时,则让用户手工填写该值,即显示的是文本框. 前段jsp使用if标签如下 ...

  4. androids-addjavascriptinterface-equivalent-in-ios

    http://stackoverflow.com/questions/7103159/androids-addjavascriptinterface-equivalent-in-ios

  5. laravel中间件-----------middleware

    middleware中间件 是访问到达服务器后在被对应的路由处理之前所经过的一层过滤层,故称中间件. 中间件是存放在app\http\middleware中,需要定一个 handle 处理方法,在ha ...

  6. [codeforces 339]E. Three Swaps

    [codeforces 339]E. Three Swaps 试题描述 Xenia the horse breeder has n (n > 1) horses that stand in a ...

  7. PYTHON seek()tell()语句

    print(f.tell()) # 显示当前位置 f.seek(0) #回到某一起点

  8. js ajax简单使用

    文章部分资源来源:(http://blog.csdn.net/lzkkevin/article/details/6777474)以及(http://www.cnblogs.com/hwx0807/ar ...

  9. Delphi中window消息截获的实现方式(2)

    Delphi是Borland公司提供的一种全新的WINDOWS编程开发工具.由于它采用了具有弹性的和可重用的面向对象Pascal(object-orientedpascal)语言,并有强大的数据库引擎 ...

  10. Delphi Dll 消息处理

    转载:http://blog.csdn.net/lailai186/article/details/8770643 事情的导火线是GIF图片的显示. 在应用程序中, 利用三方的GIFImage.pas ...