【发布时间】:2012-09-30 00:40:44
【问题描述】:
我在使用一个函数而不是使用多个函数时遇到了一些麻烦。
如果我想获得像 2^3 这样的重复排列。 permutations with repeats
得到:
000
001
101
011
100
101
110
111
我可以有这个功能:
static void Main(string[] args)
{
three_permutations(2);
Console.ReadLine();
}
static void three_permutations(int y)
{
for (int aa = 0; aa < y; aa++)
{
for (int bb = 0; bb < y; bb++)
{
for (int cc = 0; cc < y; cc++)
{
Console.Write((aa));
Console.Write((bb));
Console.Write((cc));
Console.WriteLine();
}
}
}
}
但是做4(比如2^4),我能想到的唯一方法是:
static void four_permutations(int y)
{
for (int aa = 0; aa < y; aa++)
{
for (int bb = 0; bb < y; bb++)
{
for (int cc = 0; cc < y; cc++)
{
for (int dd = 0; dd < y; dd++)
{
Console.Write((aa));
Console.Write((bb));
Console.Write((cc));
Console.Write((dd));
Console.WriteLine();
}
}
}
}
}
但我确信使用递归有更好的方法我只是不知道该怎么做。我很感激任何帮助。谢谢。
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
请查看来自en.wikipedia.org/wiki/Permutations 的链接。还有大量关于排列的印刷和在线信息,因此搜索现有的知识体系可能是个好主意。
标签: c# recursion permutation