How to get all subsets of an array?

前端 未结 12 2506
既然无缘
既然无缘 2020-11-27 17:54

Given an array: [dog, cat, mouse]

what is the most elegant way to create:

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


        
12条回答
  •  悲&欢浪女
    2020-11-27 18:03

     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]);
    }
    

提交回复
热议问题