您的位置:首页 > 其它

22. Generate Parentheses

2018-01-23 10:01 295 查看


22. Generate Parentheses

DescriptionHintsSubmissionsDiscussSolution

DiscussPick
One

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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

卡特兰数:
class Solution
{
private:
void generate(int leftNum,int rightNum,string s,vector<string> &result)
{
if(leftNum==0&&rightNum==0)
{
result.push_back(s);
}
if(leftNum>0)
{
generate(leftNum-1,rightNum,s+'(',result);
}
if(rightNum>0&&leftNum<rightNum)
{
generate(leftNum,rightNum-1,s+')',result);
}
}
public:
vector<string> generateParenthesis(int n)
{
vector<string>ans;
generate(n, n, "", ans);
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: