开发者

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

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 becau开发者_如何学Cse this code will be executed on a fairly large set of data.

Thanks!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜