核心是必须要先有一个左括号才能给字符串添加括号,且无论何时右括号的个数一定要小于等于左括号的个数
而且函数参数最好不要使用引用,方便临时变量的赋值。
C++代码如下
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
if(n<=0)
return res;
//肯定要先定义一个左括号
int zuo=0,you=0;//左括号的个数为0,但肯定是先有左括号
shengcheng(res,"(",n,1,0);
return res;
}
void shengcheng(vector<string> &res,string out,int index,int zuo,int you)
{
if(you>zuo||zuo>index||you>index)
{
return;
}
if(zuo==you&&zuo==index)
{
res.push_back(out);
}
else
{
shengcheng(res,out+'(',index,zuo+1,you);
shengcheng(res,out+')',index,zuo,you+1);
}
}
};