您的位置:首页 > 其它

[leetcode]Generate Parentheses

2014-05-03 14:24 363 查看


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

解题思路:卡特兰数变形
void innerGenerateParenthesis(vector<string> &vs, string &str, int lc, int rc, int n){
if(lc == n && rc == n){
vs.push_back(str);
return;
}
if(lc < n){
str.push_back('(');
innerGenerateParenthesis(vs, str, lc + 1, rc, n);
str.pop_back();
}
if(rc < n && rc < lc){//入栈的左括号一定要大于等于右括号数
str.push_back(')');
innerGenerateParenthesis(vs, str, lc, rc + 1, n);
str.pop_back();
}
}
vector<string> generateParenthesis(int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<string> vs;
string str; //暂存变量
innerGenerateParenthesis(vs, str, 0, 0, n);
return vs;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: