【问题标题】:All permutations of a list [duplicate]列表的所有排列[重复]
【发布时间】:2013-02-15 12:09:18
【问题描述】:

我希望能够获得这样的清单

var list=new List<int>{0, 1, 2};

得到这样的结果

var result=
    new List<List<int>>{
        new List<int>{0, 1, 2},
        new List<int>{0, 2, 1},
        new List<int>{1, 0, 2},
        new List<int>{1, 2, 0},
        new List<int>{2, 0, 1},
        new List<int>{2, 1, 0}
    };

我对缺少数字的集合不感兴趣,只对现有数字的组合感兴趣。有什么想法吗?


另外,我已经研究过Getting all possible combinations from a list of numbers 之类的解决方案,但它们不适合。

那个给了我这样的东西

var result=
    new List<List<int>> {
        // [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
        // serialized the result to JSON so it would be quicker.
    };

而且它不会吐出所有的组合。


【问题讨论】:

标签: c# combinations


【解决方案1】:

在尺寸上尝试这些扩展方法:

public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> sequence)
{
    if (sequence == null)
    {
        yield break;
    }

    var list = sequence.ToList();

    if (!list.Any())
    {
        yield return Enumerable.Empty<T>();
    }
    else
    {
        var startingElementIndex = 0;

        foreach (var startingElement in list)
        {
            var index = startingElementIndex;
            var remainingItems = list.Where((e, i) => i != index);

            foreach (var permutationOfRemainder in remainingItems.Permute())
            {
                yield return permutationOfRemainder.Prepend(startingElement);
            }

            startingElementIndex++;
        }
    }
}

【讨论】:

  • 是的,我认为你赢了。
  • 这看起来不错,但你从哪里得到 AllExcept 方法?
  • @MelbourneDeveloper 老实说,我不记得六年前的事了,我很抱歉。
  • 我意识到这有点晚了,但请注意这里提供的AllExcept 方法可以完全替换为list.Where((e,i) =&gt; i != startingElementIndex),这比手动迭代要快得多。编辑:如果您多次执行结果可枚举,也不会遇到问题
  • @MikeCaron 优雅而简洁。好电话!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 2014-02-17
相关资源
最近更新 更多