值列表的所有可能组合 [英] All Possible Combinations of a list of Values

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

问题描述

我在我的C#程序整数列表。但是,我知道在我的名单上有项目的数量仅在运行时。

I have a list of integers in my C# program. However, I know the number of items I have in my list only at runtime.

让我们说,为简单起见,我的表为{1,2,3}
现在我需要如下产生所有可能的组合。
{1,2,3}
{1,2}
{1,3}
{2,3}
{1}
{2}
{3}

Let us say, for the sake of simplicity, my list is {1, 2, 3} Now I need to generate all possible combinations as follows. {1, 2, 3} {1, 2} {1, 3} {2, 3} {1} {2} {3}

有人可以请帮助呢?

推荐答案

试试这个:

static void Main(string[] args)
{

    GetCombination(new List<int> { 1, 2, 3 });
}

static void GetCombination(List<int> list)
{
    double count = Math.Pow(2, list.Count);
    for (int i = 1; i <= count - 1; i++)
    {
        string str = Convert.ToString(i, 2).PadLeft(list.Count, '0');
        for (int j = 0; j < str.Length; j++)
        {
            if (str[j] == '1')
            {
                Console.Write(list[j]);
            }
        }
        Console.WriteLine();
    }
}

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

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