Algorithm for: All possible ways of splitting a set of elements into two sets?

本秂侑毒 提交于 2019-12-12 19:13:16

问题


I have n elements in a set U (lets assume represented by an array of size n). I want to find all possible ways of dividing the set U into two sets A and B, where |A| + |B| = n.

So for example, if U = {a,b,c,d}, the combinations would be:

  1. A = {a} -- B = {b,c,d}
  2. A = {b} -- B = {a,c,d}
  3. A = {c} -- B = {a,b,d}
  4. A = {d} -- B = {a,b,c}
  5. A = {a,b} -- B = {c,d}
  6. A = {a,c} -- B = {b,d}
  7. A = {a,d} -- B = {b,c}

Note that the following two cases are considered equal and only one should be computed:

Case 1: A = {a,b} -- B = {c,d}

Case 2: A = {c,d} -- B = {a,b}

Also note that none of the sets A or B can be empty.

The way I'm thinking of implementing it is by just keeping track of indices in the array and moving them step by step. The number of indices will be equal to the number of elements in the set A, and set B will contain all the remaining un-indexed elements.

I was wondering if anyone knew of a better implementation. Im looking for better efficiency because this code will be executed on a fairly large set of data.

Thanks!


回答1:


Take all the integers from 1 to 2^(n-1), non-inclusive. So if n = 4, the integers from 1 to 7.

Each of these numbers, written in binary, represents the elements present in set A. Set B consists of the remaining elements. Note that since we're only going to 2^(n-1), not 2^n, the high bit is always set for set B; we're always putting the first element in set B, since you want order not to matter.



来源:https://stackoverflow.com/questions/6999460/algorithm-for-all-possible-ways-of-splitting-a-set-of-elements-into-two-sets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!