【发布时间】:2021-07-06 18:18:09
【问题描述】:
我想用迭代版本替换这个函数。 我发现了一些接受唯一输入的版本。
private static void FindCombinations(char[] A, string output, ref int counter, int i, int n, int k)
{
//Console.WriteLine($"i:{i} n:{n} k:{k} r:{output}");
if (k == 0)
{
Console.WriteLine(output);
counter++;
return;
}
for (int j = i; j < n; j++)
{
FindCombinations(A, output + " " + A[j].ToString(), ref counter, j + 1, n, k - 1);
while (j < n - 1 && A[j] == A[j + 1])
j++;
}
}
private static void Main(string[] args)
{
string output = "";
char[] keys = new char[] { 'A', 'A', 'B', 'C', 'D' };
int count = 0;
FindCombinations(keys, output, ref count, 0, keys.Length, 3);
Console.WriteLine(count.ToString());
Console.ReadKey();
}
【问题讨论】:
-
你能告诉我们你到目前为止所做的尝试吗?此外,如果您能用语言解释该方法应该做什么,那也会有所帮助。
-
这个算法来自techiedelight.com/find-distinct-combinations-of-given-length,我刚刚激活了输入有重复值的选项
-
好极了,虽然最好用你自己的话写出来。请edit您的问题并将信息放在那里而不是链接(一个好的问题应该解释问题本身)。还请添加您所做的尝试。
标签: c# recursion iteration combinations