Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all the subsets of a set

I need an algorithm to find all of the subsets of a set where the number of elements in a set is n.

S={1,2,3,4...n} 

Edit: I am having trouble understanding the answers provided so far. I would like to have step-by-step explanation of how the answers work to find the subsets.

For example,

S={1,2,3,4,5} 

How do you know {1} and {1,2} are subsets?

Could someone help me with a simple function in c++ to find subsets of {1,2,3,4,5}

like image 274
Rahul Vyas Avatar asked Apr 08 '09 08:04

Rahul Vyas


People also ask

What is subset of A ={ 1 2 3?

The number of subsets that can be created from the set {1, 2, 3} is 8.

How many subsets does 12345 have?

Answer: The set {1, 2, 3, 4, 5} has 32 subsets and 31 proper subsets.

How many subsets does a set with 7 elements have?

For each subset it can either contain or not contain an element. For each element, there are 2 possibilities. Multiplying these together we get 27 or 128 subsets.

How many subsets are in a set with 6 elements?

Summary: The subsets that can be made from a set of six elements, including the null set and the set itself, are 64.


1 Answers

It's very simple to do this recursively. The basic idea is that for each element, the set of subsets can be divided equally into those that contain that element and those that don't, and those two sets are otherwise equal.

  • For n=1, the set of subsets is {{}, {1}}
  • For n>1, find the set of subsets of 1,...,n-1 and make two copies of it. For one of them, add n to each subset. Then take the union of the two copies.

Edit To make it crystal clear:

  • The set of subsets of {1} is {{}, {1}}
  • For {1, 2}, take {{}, {1}}, add 2 to each subset to get {{2}, {1, 2}} and take the union with {{}, {1}} to get {{}, {1}, {2}, {1, 2}}
  • Repeat till you reach n
like image 181
Michael Borgwardt Avatar answered Oct 02 '22 17:10

Michael Borgwardt