How to generate the power-set of a given List?

后端 未结 8 1576
南方客
南方客 2020-11-29 05:58

I\'m trying to generate a collection of all 2^N - 1 possible combinations of a given List of length N. The collection will map the number of elements in a combination to an

8条回答
  •  再見小時候
    2020-11-29 06:34

    What you're asking is generating all possible subsets of a set. You can think of it as iterating over all possible binary arrays of size N (the size of your list):

    000000...000
    000000...001
    000000...010
    000000...011
    etc.
    

    Why is that? The answer is simple: 1 indicates that an element exists in a subset, while 0 indicates that it is absent.

    So, the basic algorithm is obvious:

    s = [A, B, C, D]
    
    for i=0 to 2^N-1:
       b = convert_number_to_bin_array(i)
       ss = calculate_subset_based_on_bin_array(s, b)
       print ss
    

    Where calculate_subset_based_on_bin_array iterates on b and s and selects elements from s[current] where b[current] = 1.

    The above will print out all existing subsets. You can adapt this algorithm in order to get the map that you've asked for in your question.

提交回复
热议问题