思路:回溯
用一个con_left记录左括号的数量,用num记录最终还需要匹配的右括号数目,index记录当前位置。当左括号数量大于等于n的时候,把剩余所需要的右括号数目添加到字符串当中,再把字符串添加到容器当中。
注意每添加一次左括号,con_left与num都加一,加一次右括号(在num大于0的时候),con_left不变,num减一
cpp代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
vector<string> res;
string temp;
void dfs(int index,int n,int con_left,int num){
if(con_left>=n){
int large=temp.size();
for(int i=0;i<num;i++){
temp.append(")");
}
res.push_back(temp);
temp.erase(large,num);
return;
}
temp.append("(");
dfs(index+1,n,con_left+1,num+1);
temp.erase(index,1);
if(num>0){
temp.append(")");
dfs(index+1,n,con_left,num-1);
temp.erase(index,1);
}
return;
}
vector<string> generateParenthesis(int n)
{
temp.append("(");
dfs(1,n,1,1);
return res;
}
int main(){
int n;
cin>>n;
res=generateParenthesis(n);
for(int i=0;i<res.size();i++){
cout<<res[i]<<endl;
}
system("pause");
return 0;
}