2

Given a list of specific subsets like

S = [ {1, 2}, {3, 4}, {1}, {2, 3}, {4}, {3} ]

and a "universe" set like

U = {1, 2, 3, 4}

what elegant and simple algorithm can be used to find all the possible partitions of U made of sets from S? With this example, such partitions include

{1, 2} {3, 4}
{1, 2} {3} {4}

etc.

casperOne
  • 73,706
  • 19
  • 184
  • 253
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260

1 Answers1

1

Use recursion.

Split the problem into two smaller problems based on whether the first element is used or not:

  • Partition using {1,2} and any of the the remaining sets.
  • Partition without using {1,2} but using any of the the remaining sets.

These two options cover all possibilities.

  • The first is solved by partitioning {3,4} using only [ {3, 4}, {1}, {2, 3}, {4}, {3} ].
  • The second is solved by partitioning {1,2,3,4} using only [ {3, 4}, {1}, {2, 3}, {4}, {3} ].

To see how to solve these smaller problems refer to this similar question.

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 1
    Of course, to solve the first option, you need to first remove any sets whose intersection with `{1, 2}` is nonempty before the recursive call. For large problems, this also feels like a good candidate for some kind of memoization / dynamic programming to avoid repeated work (when you've come up with different partitions of the same subset and need to partition the rest). – Danica May 26 '12 at 22:33
  • Thanks! I did feel stupid, while reading this answer. :) Initially, I had thought of doing the first step in this answer (partitions that include {3, 4}), but with a loop on all the subsets (i.e. find all the partitions that contain a particular subset); however, this results in duplicated partitions (like {1}, {2, 3}, {4} and {4}, {2, 3}, {1}). I guess stupidity is sometimes the price to pay when posting a question right after waking up at 5 AM… :) – Eric O. Lebigot May 27 '12 at 01:48