您的位置:首页 > 其它

【LeetCode】Generate Parentheses

2014-06-04 23:33 369 查看
题目描述:

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的所有组合,可以对n-1的每个字符串从最低位到最高位插入"()",用set去重,不过这样重复很多。
class Solution {
public:
unordered_set<string> dup;
vector<string> generateParenthesis(int n) {
if (n == 1)
return vector<string>(1,"()");
vector<string> res;
vector<string> s = generateParenthesis(n - 1);
for (int i = 0; i < s.size(); i++){
for (int j = 0; j <= s[i].length(); j++){
string temp = s[i];
temp = temp.insert(j, "()");
if (dup.count(temp))
continue;
res.push_back(temp);
dup.insert(temp);
}
}
return res;
}
};
还有关于卡特兰数的方法看这里,学习中……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: