【问题标题】:Recursively get all possible permutations from an array递归地从数组中获取所有可能的排列
【发布时间】:2014-09-07 16:07:41
【问题描述】:

我有一个 char 数字数组:

static char[] numbers = {'0','1','2','3','4','5','6','7','8','9'};

我需要创建一个函数,将它们组合成所有可能的组合,最多 3 位数字。像这样:

0
1
2
3
00
01
02
03
10
11
12
13
20
21
22
23
30
31
32
33
000
001
002
003
010
011

这样,但有所有可能的组合。 到目前为止,我已经使用了 for 循环,里面有 if 但我发现使用递归函数会更好 最好和最快的方法是什么?

【问题讨论】:

  • 简短易读还是快速?你可以使用这个快速实现,也值得一读:codeproject.com/Articles/26050/…
  • 该任务所用的计算机时间最快,但也是最好的编码方式。
  • 除非你想要并行编程,最好的办法是按照你自然的方式来做——一个从字符 0 到 9 开始的函数,从 0 到 9 获得最多 3 个组合,对于所有字符。但是您真的必须进行基准测试才能为自己找出真正的答案。

标签: c# loops recursion


【解决方案1】:

嗯,这就是我想出的代码。

    static char[] numbers = {'0','1','2','3','4','5','6','7','8','9'};
    static bool continuar = true;

    private static void Start(int maxLength)
    {
        for (int i = 0; i <= maxLength; i++)
            Permutations(i, 0, "");
    }

    private static void Permutations(int keyLength, int position, string baseString)
    {
        bool print = true;
        if (continuar)
        {
            for (int i = 0; i < numbers .Length; i++)
            {
                string temp = baseString + numbers [i];
                if (position <= keyLength - 1)
                {
                    Permutations(keyLength, position + 1, temp);
                    print = false;
                }
                if (continuar && print)
                    Console.WriteLine(temp);
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-05
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多