给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
我总结了一下,回溯算法+剪枝大法
public IList<string> GenerateParenthesis(int n) {
var result = new List<string>();
DFS(n, n, new List<char>(), result);
return result;
}
private static void DFS(int leftCount, int rightCount, IList<char> oneResult, IList<string> result)
{
if (leftCount == 0 && rightCount == 0)
{
result.Add(new string(oneResult.ToArray()));
}
else
{
if (leftCount > 0)
{
oneResult.Add('(');
DFS(leftCount - 1, rightCount, oneResult, result);
oneResult.RemoveAt(oneResult.Count - 1);
}
if (rightCount > 0 && leftCount < rightCount)
{
oneResult.Add(')');
DFS(leftCount, rightCount - 1, oneResult, result);
oneResult.RemoveAt(oneResult.Count - 1);
}
}
}