获取集合的所有子集

时间:2012-04-29 17:46:03

标签: c# algorithm set subset

我正在尝试创建一个返回集合中所有子集的方法。

例如,如果我有集合10,20,30,我想得到以下输出

        return new List<List<int>>()
        {
            new List<int>(){10},
            new List<int>(){20},
            new List<int>(){30},
            new List<int>(){10,20},
            new List<int>(){10,30},
            new List<int>(){20,30},
            //new List<int>(){20,10}, that substet already exists
            // new List<int>(){30,20}, that subset already exists
            new List<int>(){10,20,30}
        };

因为集合也可以是字符串的集合,例如我想创建一个泛型方法。这就是我制定的based on this solution

    static void Main(string[] args)
    {
        Foo<int>(new int[] { 10, 20, 30});
    }

    static List<List<T>> Foo<T>(T[] set)
    {

        // Init list
        List<List<T>> subsets = new List<List<T>>();

        // Loop over individual elements
        for (int i = 1; i < set.Length; i++)
        {
            subsets.Add(new List<T>(){set[i - 1]});

            List<List<T>> newSubsets = new List<List<T>>();

            // Loop over existing subsets
            for (int j = 0; j < subsets.Count; j++)
            {
                var tempList = new List<T>();
                tempList.Add(subsets[j][0]);
                tempList.Add(subsets[i][0]);
                var newSubset = tempList;
                newSubsets.Add(newSubset);
            }

            subsets.AddRange(newSubsets);
        }

        // Add in the last element
        //subsets.Add(set[set.Length - 1]);
        //subsets.Sort();

        //Console.WriteLine(string.Join(Environment.NewLine, subsets));
        return null;
    }

修改

抱歉这是错的我仍然有重复...

    static List<List<T>> GetSubsets<T>(IEnumerable<T> Set)
    {
        var set = Set.ToList<T>();

        // Init list
        List<List<T>> subsets = new List<List<T>>();

        subsets.Add(new List<T>()); // add the empty set

        // Loop over individual elements
        for (int i = 1; i < set.Count; i++)
        {
            subsets.Add(new List<T>(){set[i - 1]});

            List<List<T>> newSubsets = new List<List<T>>();

            // Loop over existing subsets
            for (int j = 0; j < subsets.Count; j++)
            {
                var newSubset = new List<T>();
                foreach(var temp in subsets[j])
                    newSubset.Add(temp);

                newSubset.Add(set[i]);


                newSubsets.Add(newSubset);
            }

            subsets.AddRange(newSubsets);
        }

        // Add in the last element
        subsets.Add(new List<T>(){set[set.Count - 1]});
        //subsets.Sort();

        return subsets;
    }

然后我可以将该方法称为:

enter image description here

7 个答案:

答案 0 :(得分:4)

这是一个基本的算法,我使用下面的技术制作单个玩家拼字游戏的单词解算器(报纸)。

让你的集合有n个元素。递增从0到2^n的整数。对于每个生成器编号位掩码,整数的每个位置。如果整数的i位置为1,则选择集合的i元素。对于从02^n的每个生成的整数,执行上述定位和选择将获得所有子集。

这是一篇帖子:http://phoxis.org/2009/10/13/allcombgen/

答案 1 :(得分:3)

以下是Marvin Mendes在this answer中提供的代码的改编,但是使用迭代器块重构为单个方法。

public static IEnumerable<IEnumerable<T>> Subsets<T>(IEnumerable<T> source)
{
    List<T> list = source.ToList();
    int length = list.Count;
    int max = (int)Math.Pow(2, list.Count);

    for (int count = 0; count < max; count++)
    {
        List<T> subset = new List<T>();
        uint rs = 0;
        while (rs < length)
        {
            if ((count & (1u << (int)rs)) > 0)
            {
                subset.Add(list[(int)rs]);
            }
            rs++;
        }
        yield return subset;
    }
}

答案 2 :(得分:1)

我知道这个问题有点陈旧,但我一直在寻找答案而且在这里找不到任何好处,所以我想分享这个在本博客中找到的改编方案:http://praseedp.blogspot.com.br/2010/02/subset-generation-in-c.html

我只将类转换为泛型类:

public class SubSet<T>
{
    private IList<T> _list;
    private int _length;
    private int _max;
    private int _count;

    public SubSet(IList<T> list)
    {
        if (list== null)
            throw new ArgumentNullException("lista");
        _list = list;
        _length = _list.Count;
        _count = 0;
        _max = (int)Math.Pow(2, _length);
    }


    public IList<T> Next()
    {
        if (_count == _max)
        {
            return null;
        }
        uint rs = 0;

        IList<T> l = new List<T>();            

        while (rs < _length)
        {
            if ((_count & (1u << (int)rs)) > 0)
            {
                l.Add(_list[(int)rs]);                    
            }
            rs++;
        }
        _count++;
        return l;            
    }
}

要使用此代码,您可以执行以下操作:

        List<string> lst = new List<string>();

        lst.AddRange(new string[] {"A", "B", "C" });

        SubSet<string> subs = new SubSet<string>(lst);

        IList<string> l = subs.Next();

        while (l != null)
        {

            DoSomething(l);
            l = subs.Next();
        }

请记住:此代码仍为O(2 ^ n),如果您在列表中传递20个元素,则会得到2 ^ 20 = 1048576个子集!

修改: 作为Servy sugest,我添加了一个带有interator块的实现,可以与Linq一起使用foreach,新类是这样的:

private class SubSet<T> : IEnumerable<IEnumerable<T>>
    {
        private IList<T> _list;
        private int _length;
        private int _max;
        private int _count;

        public SubSet(IEnumerable<T> list)
        {
            if (list == null)
                throw new ArgumentNullException("list");
            _list = new List<T>(list);
            _length = _list.Count;
            _count = 0;
            _max = (int)Math.Pow(2, _length);
        }

        public int Count
        {
            get { return _max; }
        }



        private IList<T> Next()
        {
            if (_count == _max)
            {
                return null;
            }
            uint rs = 0;

            IList<T> l = new List<T>();

            while (rs < _length)
            {
                if ((_count & (1u << (int)rs)) > 0)
                {
                    l.Add(_list[(int)rs]);
                }
                rs++;
            }
            _count++;
            return l;
        }

        public IEnumerator<IEnumerable<T>> GetEnumerator()
        {
            IList<T> subset;
            while ((subset = Next()) != null)
            {
                yield return subset;
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

你现在可以像这样使用它:

        List<string> lst = new List<string>();

        lst.AddRange(new string[] {"A", "B", "C" });

        SubSet<string> subs = new SubSet<string>(lst);

        foreach(IList<string> l in subs)
        {
            DoSomething(l);
        }

感谢Servy的建议。

答案 3 :(得分:0)

您不想返回一组列表,您想要使用java的set类型。通过只保留每种类型的一个唯一元素,Set已经完成了您正在寻找的部分内容。所以你不能两次添加20次。它是一种无序类型,所以你可能会做的是编写一个组合函数,它创建了一堆集合,然后返回一个包含那些集合的列表。

答案 4 :(得分:0)

获取特定子强度集合的所有子集:

    public static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length) where T : IComparable
    {
        if (length == 1) return list.Select(t => new T[] { t });
        return GetPermutations(list, length - 1).SelectMany(t => list.Where(e => t.All(g => g.CompareTo(e) != 0)), (t1, t2) => t1.Concat(new T[] { t2 }));
    }

    public static IEnumerable<IEnumerable<T>> GetOrderedSubSets<T>(IEnumerable<T> list, int length) where T : IComparable
    {
        if (length == 1) return list.Select(t => new T[] { t });
        return GetOrderedSubSets(list, length - 1).SelectMany(t => list.Where(e => t.All(g => g.CompareTo(e) == -1)), (t1, t2) => t1.Concat(new T[] { t2 }));
    }

Testcode:

        List<int> set = new List<int> { 1, 2, 3 };
        foreach (var x in GetPermutations(set, 3))
        {
            Console.WriteLine(string.Join(", ", x));
        }
        Console.WriteLine();
        foreach (var x in GetPermutations(set, 2))
        {
            Console.WriteLine(string.Join(", ", x));
        }
        Console.WriteLine();
        foreach (var x in GetOrderedSubSets(set, 2))
        {
            Console.WriteLine(string.Join(", ", x));
        }

测试结果:

1, 2, 3
1, 3, 2
2, 1, 3
2, 3, 1
3, 1, 2
3, 2, 1

1, 2
1, 3
2, 1
2, 3
3, 1
3, 2

1, 2
1, 3
2, 3

答案 5 :(得分:0)

它不会产生重复的值;

不要在子集的开头添加int数组的值

正确的程序如下:

class Program
    {
        static HashSet<List<int>> SubsetMaker(int[] a, int sum)
        {
            var set = a.ToList<int>();
            HashSet<List<int>> subsets = new HashSet<List<int>>();
            subsets.Add(new List<int>());
            for (int i =0;i<set.Count;i++)
            {
                //subsets.Add(new List<int>() { set[i]});
                HashSet<List<int>> newSubsets = new HashSet<List<int>>();
                for (int j = 0; j < subsets.Count; j++)
                {
                   var newSubset = new List<int>();
                   foreach (var temp in subsets.ElementAt(j))
                   {
                      newSubset.Add(temp);


                    }
                    newSubset.Add(set[i]);
                    newSubsets.Add(newSubset);

                }
                Console.WriteLine("New Subset");
                foreach (var t in newSubsets)
                {
                    var temp = string.Join<int>(",", t);
                    temp = "{" + temp + "}";
                    Console.WriteLine(temp);
                }
                Console.ReadLine();

                subsets.UnionWith(newSubsets);
            }
            //subsets.Add(new List<int>() { set[set.Count - 1] });
            //subsets=subsets.;
            return subsets;

        }
        static void Main(string[] args)
        {
            int[] b = new int[] { 1,2,3 };
            int suma = 6;
            var test = SubsetMaker(b, suma);
            Console.WriteLine("Printing final set...");
            foreach (var t in test)
            {
                var temp = string.Join<int>(",", t);
                temp = "{" + temp + "}";
                Console.WriteLine(temp);
            }
            Console.ReadLine();

        }
    }

答案 6 :(得分:0)

基于递归的简单算法:

private static List<List<int>> GetPowerList(List<int> a)
    {
        int n = a.Count;
        var sublists = new List<List<int>>() { new List<int>() };
        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;
    }