给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
class Solution {
private:
/*
注意此处的string strTemp不能为引用,否则会有“非常量引用的初始值必须是左值“的错误信息
*/
void dfs(vector<string> &vecRes, string strTemp, int count1, int count2, int n)
{
if(count1 > n || count2 > n) return; //防止越界,无限递增下去
if(count1 == n && count2 == n)
{
vecRes.push_back(strTemp);
return;
}
if(count1 >= count2) //注意此处是count1 >= count2,由于是全排列,剔除掉右括号在左括号前的情况
{
dfs(vecRes, strTemp+'(', count1+1, count2, n);
dfs(vecRes, strTemp+')', count1, count2+1, n);
}
}
public:
vector<string> generateParenthesis(int n) {
vector<string> vecRes;
string strTemp = "";
dfs(vecRes, strTemp, 0, 0, n);
return vecRes;
}
};
错误引用示例:
void increment(double& x)
{
x += 1.0;
}
increment(5); //编译错误
因为increment()函数的形参是double&,而调用时的实参是整形常量。因此,调用increment()函数时实际上存在一个隐式的类型转换
double& temp = (double)5;
x = temp;
假设此后在increment()中对形参x进行修改,实际上就是对常量进行了修改,这显然是不能允许的。所以,在对非常量进行初始化时,该初始值必须是左值,而不能是右值。因此,会显示“非常量引用的初始值必须是左值”的错误信息。