Generate Parentheses
题意是要求生成匹配的括号结果。假如给定n = 3,需要生成3对括号的有效组合,即"((()))", "(()())", "(())()", "()(())", "()()()"。
void unguarded_generate(vector<string> &result, string curr, int m, int n)
{
if (m == 0 && n == 0)
{
result.push_back(curr);
}
else
{
if (m != 0)
{
unguarded_generate(result, curr + "(", m - 1, n);
}
if (m < n && n != 0)
{
unguarded_generate(result, curr + ")", m, n - 1);
}
}
}
vector<string> generateParenthesis(int n)
{
vector<string> ret;
if (n > 0)
{
unguarded_generate(ret, string(), n, n);
}
return ret;
}