How to get all subsets of an array?

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

    The way this is written, it is more of a Product (Cartesian product) rather than a list of all subsets.

    You have three sets: (Empty,"dog"), (Empty,"cat"),(Empty,"mouse").

    There are several posts on general solutions for products. As noted though, since you really just have 2 choices for each axis a single bit can represent the presence or not of the item.

    So the total set of sets is all numbers from 0 to 2^N-1. If N < 31 an int will work.

提交回复
热议问题