您描述的方法适用于 f(1) 和 f(2)。对于 n > 2,它不会遗漏任何一个,但会产生重复。
对于 f(3),这是开始生成重复项的时间。在 f(2) 的基础上,您有“()()”和“(())”的 2 个解决方案。当您在该算法之后插入括号时,最终这两个解决方案都会生成“()(())”。由于这个重复,你最终得到了 f(3) 的 6 个解,而不是实际的 5 个。
如果将该算法应用于 f(5),它将生成 f(1) 到 f(5) 的 33 个总解。应该只有 22 个解决方案,因此您会得到 10 个重复项。
有一个非常常见的递归解决方案,涉及计算多个括号的打开和关闭。我见过的最好的解释是https://anonymouscoders.wordpress.com/2015/06/16/all-balanced-permutation-of-number-of-given-parentheses/
以下是 C 语言解决方案之一的示例:
// Source: http://www.geeksforgeeks.org/print-all-combinations-of-balanced-parentheses/
# include<stdio.h>
# define MAX_SIZE 100
void _printParenthesis(int pos, int n, int open, int close);
/* Wrapper over _printParenthesis()*/
void printParenthesis(int n)
{
if(n > 0)
_printParenthesis(0, n, 0, 0);
return;
}
void _printParenthesis(int pos, int n, int open, int close)
{
static char str[MAX_SIZE];
if(close == n)
{
printf("%s \n", str);
return;
}
else
{
if(open > close) {
str[pos] = '}';
_printParenthesis(pos+1, n, open, close+1);
}
if(open < n) {
str[pos] = '{';
_printParenthesis(pos+1, n, open+1, close);
}
}
}
/* driver program to test above functions */
int main()
{
int n = 4;
printParenthesis(n);
getchar();
return 0;
}
作为参考,这是我为您提供的算法所做的 C# 版本:
// Initial funtion call
void f(int n)
{
f(1, n, "");
}
// Recursive call
void f(int n, int max, string output)
{
for (int i = 0; i < output.Length; i++)
{
if (output[i] == '(')
{
var inserted = output.Insert(i + 1, "()");
Console.WriteLine(inserted);
if (n < max)
f(n + 1, max, inserted);
}
}
// Pre-pend parens
output = "()" + output;
Console.WriteLine(output);
if (n < max)
f(n + 1, max, output);
}
f(4);
链接:https://dotnetfiddle.net/GR5l6C