如何获得一个数组的所有子集? [英] How to get all subsets of an array?

查看:422
本文介绍了如何获得一个数组的所有子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个数组: [狗,猫,鼠]

什么是最优雅的方式来创建:

  [,,]
[,,老鼠]
[,猫,]
[,猫,鼠]
[狗,,]
[狗,,鼠标]
[狗猫,]
[狗,猫,鼠]

我需要这对任何大小的数组工作。

这实质上是一个二进制计数器,其中数组索引重新present位。这presumably让我用一些位运算来算,但我不能看到,虽然翻译这数组索引的一个很好的方式。


解决方案

 的String []源=新的字符串[] {狗,猫,老鼠};
 的for(int i = 0; I< Math.Pow(2 source.Length);我++)
 {
     字符串[] =结合新的字符串[source.Length]
     对于(INT J = 0; J< source.Length; J ++)
     {
         如果((ⅰ及(1下;&下;!(source.Length - J - 1)))= 0)
         {
             组合[J] =源[J]。
         }
    }
    Console.WriteLine([{0},{1},{2}],组合[0],组合[1],组合[2]);
}

Given an array: [dog, cat, mouse]

what is the most elegant way to create:

[,,]
[,,mouse]
[,cat,]
[,cat,mouse]
[dog,,]
[dog,,mouse]
[dog,cat,]
[dog,cat,mouse]

I need this to work for any sized array.

This is essentially a binary counter, where array indices represent bits. This presumably lets me use some bitwise operation to count, but I can't see a nice way of translating this to array indices though.

解决方案

 string[] source = new string[] { "dog", "cat", "mouse" };
 for (int i = 0; i < Math.Pow(2, source.Length); i++)
 {
     string[] combination = new string[source.Length];
     for (int j = 0; j < source.Length; j++)
     {
         if ((i & (1 << (source.Length - j - 1))) != 0)
         {
             combination[j] = source[j];
         }
    }
    Console.WriteLine("[{0}, {1}, {2}]", combination[0], combination[1], combination[2]);
}

这篇关于如何获得一个数组的所有子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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