Generate Parentheses
问题描述:
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
知识补充:
引用的使用
void add_s(vector<string> &r,string str,int left ,int right)
//其中vector<string> &r,我们需要使用引用&来保证参数的传递,如果不使用引用只是一个形参对r的操作无法影响到初始的r,使用引用后相当于是r的别名,对他的操作就相当于对r本身的操作
测试代码:
int main()
{
int n = 4;
vector<string> result;
add_s(result,"",n,0);
return result;
}
void add_s(vector<string> &r,string str,int left ,int right)
{
if(left==0&&right==0)
{
r.push_back(str);
return;
}
if(left>0)
{
add_s(r,str+"(",left-1,right+1);
}
if(right>0)
{
add_s(r,str+")",left,right-1);
}
}