本题分别采用两种方法:暴力法(set+vector) 以及 dfs(vector)
vector<string> generateParenthesis(int n) {
set<string> resSet;//利用set的去重 将所有的可能放入set中 然后转换成vector
vector<string> res;
//boundary condition
if (n == 0)
return res;
resSet.insert("()");
if (n == 1)
{
res.push_back("()");
return res;
}
// !recursion
for (int i = 2; i <= n; i++)
{
set<string> resTemp = resSet;
resSet.clear();
for (auto s : resTemp)
{
//brackets is between the s 挨个插括号 每个位置都插一遍
for (int j = 0; j < s.size(); j++)
{
string left = s.substr(0, j);
string right = s.substr(j);
resSet.insert(left + "()" + right);
}
//brackets is out of the s
resSet.insert("(" + s + ")");
}
}
//take the string in the vector
for (auto s : resSet)
{
res.push_back(s);
}
return res;
}
明显的比较出DFS在时间这方面是多么高效
void DFS(vector<string> &vs, string curstr, int left, int right) //remain left '(' and right ')'
{
//boundary condition
if (left > right)//左括号剩余数量不能多余右括号
return;
if (left < 0 || right < 0)
return;
if (left == 0 && right == 0)
{
vs.push_back(curstr);
return;
}
if (left > 0) //if the left is remained ,continue traverse
DFS(vs, curstr + '(', left - 1, right);
if (right > 0)//if the right is remained ,continue traverse
DFS(vs, curstr + ')', left, right - 1);
}
vector<string> generateParenthesis(int n)
{
vector<string> res;
//boundary condition
if (n == 0)
return res;
if (n == 1)
{
res.push_back("()");
return res;
}
// DFS
DFS(res, "", n, n);//the number of '(' and ')' are both n
return res;
}