**
题目:括号生成
**
内容:
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:
输入:n = 3
输出:[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
#include<bits/stdc++.h>
using namespace std;
void dfs(string str,int left,int right,vector<string> &res)
{
if(left==0&&right==0)//结束搜索的条件
{
res.push_back(str);
return;
}
if(left>right)//除去不可能的情况
return;
if(left>0)
dfs(str+"(",left-1,right,res);
if(right>0)
dfs(str+")",left,right-1,res);
}
vector<string> generateParenthesis(int n) {
vector<string> res;//存放生成的合法的结果
if(n==0)//当n==0时,结果无结果,直接返回空的
{
return res;
}
dfs("",n,n,res);//开始进行搜索,代表左右括号的个数
return res;
}
int main()
{
int n;
cin>>n;
vector<string> vec=generateParenthesis(n);
for(int i=0;i<vec.size();i++)
{
cout<<vec[i]<<endl;
}
cout<<endl;
return 0;
}