相关疑难解决方法(0)

生成集合的排列(最有效)

我想生成一个集合(集合)的所有排列,如下所示:

Collection: 1, 2, 3
Permutations: {1, 2, 3}
              {1, 3, 2}
              {2, 1, 3}
              {2, 3, 1}
              {3, 1, 2}
              {3, 2, 1}
Run Code Online (Sandbox Code Playgroud)

一般而言,这不是"如何"的问题,而是关于如何最有效的问题.此外,我不想生成所有排列并返回它们,但一次只生成一个排列,并且只在必要时继续(很像迭代器 - 我也尝试过,但结果却少了有效).

我已经测试了很多算法和方法,并提出了这个代码,这是我尝试过的最有效的代码:

public static bool NextPermutation<T>(T[] elements) where T : IComparable<T>
{
    // More efficient to have a variable instead of accessing a property
    var count = elements.Length;

    // Indicates whether this is the last lexicographic permutation
    var done = true;

    // Go through the array from last to first
    for (var i = …
Run Code Online (Sandbox Code Playgroud)

c# algorithm optimization performance permutation

59
推荐指数
5
解决办法
5万
查看次数

标签 统计

algorithm ×1

c# ×1

optimization ×1

performance ×1

permutation ×1