How to get all subsets of an array?

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

    Easy to understand version (with descriptions)

    I assumed that source = {1,2,3,4}

    public static IEnumerable> GetSubSets(IEnumerable source)
        {
            var result = new List>() { new List() }; // empty cluster  added
    
            for (int i = 0; i < source.Count(); i++)
            {
                var elem = source.Skip(i).Take(1);
    
                // for elem = 2
                // and currently result = [ [],[1] ]
                var matchUps = result.Select(x => x.Concat(elem));
                //then matchUps => [ [2],[1,2] ]
    
                 result = result.Concat(matchUps).ToList();
                //  matchUps and result concat operation
                // finally result = [ [],[1],[2],[1,2] ]
            }
            return result;
        }
    

提交回复
热议问题