列表的所有排列

Kel*_*ton 10 c# combinations

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

var list=new List<int>{0, 1, 2};
Run Code Online (Sandbox Code Playgroud)

得到这样的结果

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}
    };
Run Code Online (Sandbox Code Playgroud)

我对缺少数字的集合感兴趣,只是存在数字的组合.有任何想法吗?


此外,我已经研究过诸如从数字列表中获取所有可能的组合之类的解决方案,但它们并不合适.

那个给了我这样的东西

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.
    };
Run Code Online (Sandbox Code Playgroud)

它并没有吐出所有的组合.


Jes*_*cer 10

尝试使用这些扩展方法的大小:

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 startingElement.Concat(permutationOfRemainder);
            }

            startingElementIndex++;
        }
    }
}

private static IEnumerable<T> Concat<T>(this T firstElement, IEnumerable<T> secondSequence)
{
    yield return firstElement;
    if (secondSequence == null)
    {
        yield break;
    }

    foreach (var item in secondSequence)
    {
        yield return item;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,我认为你赢了. (2认同)