查找列表的所有子集 [英] Find all subsets of a list

查看:203
本文介绍了查找列表的所有子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名单,我需要输出列表中的每个子集

I have a list and I need to output each subset of the list

例如ABCDE

将输出到

 a
 b
 c  
 d 
 e 
 ab  
 ac  
 ad 
 ae

 abc
 abd 
 abe
 bcd
 bce
 ....
 abcde

我认为正确的说法是组合没有元素应该在相同的复制行

I believe the correct term is combination no element should be duplicated on the same line

我会用一系列的循环来尝试这一点,但即时通讯甚至不知道wehre启动

I was going to attempt this with a series of loops but im not even sure wehre to start

有什么建议?

推荐答案

这将排序的字母结尾生成你想要的设置,但在不同的顺序(I,你会希望通过长度为好)排序

This will generate the set you want, but in a different order (I sort by alphabet at the end, you'd want to sort by length as well).

您会结了:


AB
ABC
ABCD
ABCDE
ABCE

D
去$ b $是

a ab abc abcd abcde abce ... d de e

所以,每一个可能的子集(除了空字符串),在保持原有列表的顺序。

So, every possible subset (aside from the empty string), while maintaining the order of the original list.

我们的想法是每一个元素添加到为越来越多。随着每一个新的元素,首先添加它,然后把它添加到现有的所有元素。

The idea is to add each element to to a growing list. With every new element, add it first, and then add it to all existing elements.

所以,开始与A。

进入到'B'。将其添加到列表中。我们现在有{'A','B'}

Go on to 'b'. Add it to the list. We now have {'a', 'b'}.

将它添加到现有的元素,让我们有了'抗体'。现在我们有{'A','B','AB'}

Add it to existing elements, so we have 'ab'. Now we have {'a', 'b', 'ab'}.

然后'C',并将其添加到现有元素得到'交流',' BC','ABC':{'A','b','AB','C','交流','公元前'ABC'}。 。依此类推,直到我们就大功告成了。

Then 'c', and add it to existing elements to get 'ac', 'bc', 'abc': {'a', 'b', 'ab', 'c', 'ac', 'bc', abc'}. So forth until we're done.

        string set = "abcde";

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

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

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

            // Loop over existing subsets
            for (int j = 0; j < subsets.Count; j++)
            {
                string newSubset = subsets[j] + set[i];
                newSubsets.Add(newSubset);
            }

            subsets.AddRange(newSubsets);
        }

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

        Console.WriteLine(string.Join(Environment.NewLine, subsets));

这篇关于查找列表的所有子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆