How to get all subsets of an array?

前端 未结 12 2476
既然无缘
既然无缘 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:06

    Elegant? Why not Linq it.

        public static IEnumerable> SubSetsOf(IEnumerable source)
        {
            if (!source.Any())
                return Enumerable.Repeat(Enumerable.Empty(), 1);
    
            var element = source.Take(1);
    
            var haveNots = SubSetsOf(source.Skip(1));
            var haves = haveNots.Select(set => element.Concat(set));
    
            return haves.Concat(haveNots);
        }
    

提交回复
热议问题