给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
用了集合去重 和 DFS扩展。当 搜索到n时,遇到’(’ 之后在当前串插入一个"()“就是其中一个目标值,加上“()”+当前串、当前串加上”()" 就是所有可能值。这里会存在重复的串,使用集合去重,n=1时,初始集合中仅有"()"。C++中的STL要熟练啊。
class Solution {
public:
void dfs(set<string>& s, int n)
{
auto k = s.begin();
if ((*k).length() == (n * 2))
return;
else
{
set<string> new_set;
for (auto i = s.begin(); i != s.end(); i++)
{
for (int j = 0; j < (*i).length(); j++)
{
if ((*i)[j] == '(')
new_set.insert((*i).substr(0, j + 1) + "()" + (*i).substr(j + 1));
}
new_set.insert("()" + (*i));
new_set.insert((*i) + "()");
}
s.clear();
s = new_set; //扩展的集合
dfs(s, n);
}
}
vector<string> generateParenthesis(int n)
{
vector<string> res;
set<string>s;
s.insert("()");
if (n == 0)
return res;
else
{
dfs(s, n);
for (auto i = s.begin(); i != s.end(); i++)
{
res.push_back((*i));
}
return res;
}
}
};