Get all subsets of a collection

后端 未结 7 604
青春惊慌失措
青春惊慌失措 2021-01-13 17:05

I am trying to create a method that will return all subsets of a set.

For example if I have the collection 10,20,30 I will like to get the following ou

7条回答
  •  终归单人心
    2021-01-13 17:26

    A simple algorithm based upon recursion:

    private static List> GetPowerList(List a)
        {
            int n = a.Count;
            var sublists = new List>() { new List() };
            for (int i = 0; i < n; i++)
            {
                for (int j = i; j < n; j++)
                {
                    var first = a[i];
                    var last = a[j];
                    if ((j - i) > 1)
                    {
                        sublists.AddRange(GetPowerList(a
                            .GetRange(i + 1, j - i - 1))
                            .Select(l => l
                            .Prepend(first)
                            .Append(last).ToList()));
                    }
                    else sublists.Add(a.GetRange(i,j - i + 1));
                }
            }
            return sublists;
        }
    

提交回复
热议问题