像二叉树,然后减枝。
个人开始理解为,2个括号,分别插入到2n个节点。类似图色。在减减枝条。(左右括号必须小于等于n,再者先左括号,在右括号!)
#include <iostream>
#include <vector>
#include <string>
#include <cassert>
using namespace std;
void paren(int n,int level,int count_left,int count_right,vector<string> &res,string str);
void paren_str(int n);
int main()
{
paren_str(4);
cout<<"-----------------"<<endl;
paren_str(3);
return 0;
}
void paren_str(int n)
{
if (n <= 0)
{
return;
}
vector<string> res;
string str;
paren(n,0,1,1,res,str);
for (int i = 0;i < res.size();i++)
{
cout<<res[i]<<endl;
}
}
void paren(int n,int level,int count_left,int count_right,vector<string> &res,string str)
{
if (level >= 2*n)
{
res.push_back(str);//结果保存
return ;
}
if (count_left <= n)
{
str.push_back('(');
paren(n,level+1,count_left+1,count_right,res,str);//左括号
str.erase(str.size()-1,1);
}
if(level == 0) return;
if (count_right <= n && count_left > count_right)//左边括号必须先出现
{
str.push_back(')');
paren(n,level+1,count_left,count_right+1,res,str);//右括号
str.erase(str.size()-1,1);
}
}