您的位置:首页 > 其它

[leetcode]Generate Parentheses

2015-01-22 20:07 295 查看
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:

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


题目是要生成所有的匹配的括号序列: 左括号和右括号的数目都为n, 序列的任意位置index之前(左边的)的左括号总数都是要大于或者等于右括号总数。

总的序列的数目应该是卡特兰数:h(n)=C(2n,n)/(n+1) (n=0,1,2,...)或者h(n)=c(2n,n)-c(2n,n+1)(n=0,1,2,...)

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;

void help(int total, int left, int right, string str, vector<string>& svec)
{
if(left>total || right>total || right>left)
return;
if(total==right&&left==total)
{
svec.push_back(str);
return;
}
else
{
if(left<total)
help(total, left+1, right, str+"(", svec);
if(right<left&&left<=total)
help(total, left, right+1, str+")", svec);
}
}

vector<string> generateParenthesis(int n) {
vector<string> svec;
help(n, 0, 0, "", svec);

return svec;
}

int main()
{
vector<string> svec;
svec=generateParenthesis(3);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: