您的位置:首页 > 其它

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: