leetcode 22. Generate Parentheses
2016-03-20 23:21
405 查看
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 {
void do_once(set<string>&candi)
{
set<string>newcandi; set<string>hist;
for (set<string>::iterator it = candi.begin(); it != candi.end(); it++)
{
string str = *it;
for (int j = 0; j <= str.length(); j++)
{
string s = str;
s.insert(s.begin() + j, '(');
if (hist.find(s) == hist.end())
{
hist.insert(s);
for (int h = j + 1; h <= s.length(); h++)
{
string ss = s;
ss.insert(ss.begin() + h, ')');
if (newcandi.find(ss) == newcandi.end())
newcandi.insert(ss);
}
}
}
}
candi = newcandi;
}
public:
vector<string> generateParenthesis(int n) {
vector<string>re;
if (n == 0)
return re;
set<string>candi;
candi.insert("()");
while (n > 1)
{
do_once(candi);
n--;
}
return vector<string>(candi.begin(), candi.end());
}
};
accepted
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
class Solution {
void do_once(set<string>&candi)
{
set<string>newcandi; set<string>hist;
for (set<string>::iterator it = candi.begin(); it != candi.end(); it++)
{
string str = *it;
for (int j = 0; j <= str.length(); j++)
{
string s = str;
s.insert(s.begin() + j, '(');
if (hist.find(s) == hist.end())
{
hist.insert(s);
for (int h = j + 1; h <= s.length(); h++)
{
string ss = s;
ss.insert(ss.begin() + h, ')');
if (newcandi.find(ss) == newcandi.end())
newcandi.insert(ss);
}
}
}
}
candi = newcandi;
}
public:
vector<string> generateParenthesis(int n) {
vector<string>re;
if (n == 0)
return re;
set<string>candi;
candi.insert("()");
while (n > 1)
{
do_once(candi);
n--;
}
return vector<string>(candi.begin(), candi.end());
}
};
accepted
相关文章推荐
- 多线程_互斥锁解决买票问题
- ubuntu 安装 rtl8188驱动
- 2552: 好好学习天天向上
- 我的c++第二次程序1
- Java - 反射
- 两个命令把 Vim 打造成 Python IDE的方法
- 14. 发送邮件
- Unable to obtain debug bridge
- 第三周JAVA程序设计基础学习总结
- 读C#程序(第三周)
- LightOJ 1234 Harmonic Number
- 固定位数和精度的浮点数处理对象Decimal
- Swift语言学习笔记(3)
- crond job curl 运行单参数的url出错
- Jfinal 实现从数据库中提取图片
- 2016春季练习——优先队列的一个神奇用法
- 程序员面试资源大收集
- 2502: How many roses can he buy?
- PHP之cookie
- Qt正则表达式笔记