思路:
DFS一波带走,输入n后,那么括号的总数量肯定是2n,所以进行全排列,然后从所有的组合中找出合适的放入vector容器中,这个方法应该算是比较简单的,所以时间复杂度和空间复杂度……唉
反思:
代码千万条,方法第一条,算法不学好,做题两行泪。
#include<iostream>
#include<vector>
using namespace std;
class Solution
{
public:
int length = 0;
vector<string> generateParenthesis(int n)
{
string str = "";
length = 2*n;
DFS(str,0);
return strVector;
}
private:
vector<string> strVector;
bool isValid(string str)
{
int flag = 0;
for(int i=0; i<str.size(); i++)
{
if(str[i] == '(')
flag++;
else
flag--;
if(flag<0)
return false;
}
if(flag == 0)
return true;
else
return false;
}
void DFS(string str,int len)
{
if(len == length)
{
if(isValid(str))
strVector.push_back(str);
return;
}
DFS(str+'(',len+1);
DFS(str+')',len+1);
}
};
int main()
{
Solution s;
vector<string> strVector;
strVector = s.generateParenthesis(2);
vector<string>::iterator it;
for(it=strVector.begin();it!=strVector.end();it++)
{
cout<<*it<<endl;
}
return 0;
}
经过一番折腾,稍微改进了一下
class Solution
{
public:
vector<string> generateParenthesis(int n)
{
string str = "";
DFS(str,n,n);
return strVector;
}
private:
vector<string> strVector;
void DFS(string str,int L,int R)
{
if(L>R || L<0 || R<0)
return ;
if(L==R && L==0)
strVector.push_back(str);
DFS(str+'(',L-1,R);
DFS(str+')',L,R-1);
}
};