列表的所有排列 [英] All permutations of a list

查看:78
本文介绍了列表的所有排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够接受这样的列表

I'd like to be able to take a list like this

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}
    };

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

I'm not interested in sets with missing numbers, just combinations of the numbers that exist. Any ideas?

此外,我还研究了已从数字列表中获取所有可能的组合,但它们不合适。

Also, I've looked into solutions like Getting all possible combinations from a list of numbers already, and they don't fit.

那个给了我这样的东西

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.
    };

它并不会吐出所有组合。

And it doesn't spit out all of the combinations.

推荐答案

尝试以下扩展方法以获取大小:

Try these extension methods on for size:

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;
    }
}

这篇关于列表的所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆