Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
此题已做过:打印n对括号匹配的所有组合
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> generateParenthesis(int n);
void praren_match_find(int n,int left_num,int right_num,int level,string str,vector<string> &res);
int main()
{
int n;
cin>>n;
vector<string> res = generateParenthesis(n);
cout<<res.size()<<endl;
for(int i = 0;i < res.size();i++)
{
cout<<res[i]<<endl;
}
return 0;
}
vector<string> generateParenthesis(int n)
{
if(n <= 0)return vector<string>();
string str ;
vector<string> res;
praren_match_find(n,0,0,0,str,res);
return res;
}
void praren_match_find(int n,int left_num,int right_num,int level,string str,vector<string> &res)
{
if(level >= 2*n)
{
res.push_back(str);
return ;
}
//if(left_num >= n)return ;//将报错,得不到结果,因为将以下整层全切掉了,包括右子树!
if(left_num < n)
{
praren_match_find(n,left_num+1,right_num,level+1,str+'(',res);
}
if(left_num > right_num)
{
praren_match_find(n,left_num,right_num+1,level+1,str+')',res);
}
}