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,要求写一个方法,生成所有n个括号的可能合法组合。
#include "GenerateParentheses.h"
vector<string> GenerateParentheses::generateParenthesis(int m)
{
vector<string> res;
addParenthesis(res, "", m, 0);
return res;
}
void GenerateParentheses::addParenthesis(vector<string> &v, string str, int m, int n)
{
// m表示要继续增加括号的对数,n表示所需右括号个数
//在增加括号的过程中保证右括号的个数始终不多于左括号的个数就能满足合法的条件
if (m == 0 && n == 0)
{
v.push_back(str);
return;
}
if (n > 0)
{
//增加右括号,右括号需要个数减1
addParenthesis(v, str + ")", m, n - 1);
}
if (m > 0)
{
//增加左括号,所需增加的括号对数减1,右括号所需个数加1
addParenthesis(v, str + "(", m - 1, n + 1);
}
}