How to get all subsets of an array?

前端 未结 12 2509
既然无缘
既然无缘 2020-11-27 17:54

Given an array: [dog, cat, mouse]

what is the most elegant way to create:

[,,]
[,,mouse]
[,cat,]
[,cat,mouse]
[dog,,]
[dog,,mouse]
[dog,         


        
12条回答
  •  天涯浪人
    2020-11-27 18:08

    Here is a variant of mqp's answer, that uses as state a BigInteger instead of an int, to avoid overflow for collections containing more than 30 elements:

    using System.Numerics;
    
    public static IEnumerable> GetSubsets(IList source)
    {
        BigInteger combinations = BigInteger.One << source.Count;
        for (BigInteger i = 0; i < combinations; i++)
        {
            yield return Enumerable.Range(0, source.Count)
                .Select(j => (i & (BigInteger.One << j)) != 0 ? source[j] : default);
        }
    }
    

提交回复
热议问题