How to get all subsets of an array?

前端 未结 12 2493
既然无缘
既然无缘 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:26

    I'm not very familiar with C# but I'm sure there's something like:

    // input: Array A
    foreach S in AllSubsetsOf1ToN(A.Length): 
        print (S.toArray().map(lambda x |> A[x]));
    

    Ok, I've been told the answer above won't work. If you value elegance over efficiency, I would try recursion, in my crappy pseudocode:

    Array_Of_Sets subsets(Array a) 
    {
        if (a.length == 0) 
             return [new Set();] // emptyset
        return subsets(a[1:]) + subsets(a[1:]) . map(lambda x |> x.add a[0]) 
    }
    

提交回复
热议问题