Power Set

Power set of a set S is the set of all of the subsets of S, including the empty set and S itself. Power set of set S is denoted as P(S).

For example for {x, y, z}, the subsets are:

  1. {
  2. {}, // (also denoted empty set ∅ or the null set)
  3. {x},
  4. {y},
  5. {z},
  6. {x, y},
  7. {x, z},
  8. {y, z},
  9. {x, y, z}
  10. }

Power Set

Here is how we may illustrate the elements of the power set of the set {x, y, z} ordered with respect to inclusion:

Power Set - 图2

Number of Subsets

If S is a finite set with |S| = n elements, then the number of subsets of S is |P(S)| = 2^n. This fact, which is the motivation for the notation 2^S, may be demonstrated simply as follows:

First, order the elements of S in any manner. We write any subset of S in the format {γ1, γ2, ..., γn} where γi , 1 ≤ i ≤ n, can take the value of 0 or 1. If γi = 1, the i-th element of S is in the subset; otherwise, the i-th element is not in the subset. Clearly the number of distinct subsets that can be constructed this way is 2^n as γi ∈ {0, 1}.

Algorithms

Bitwise Solution

Each number in binary representation in a range from 0 to 2^n does exactly what we need: it shows by its bits (0 or 1) whether to include related element from the set or not. For example, for the set {1, 2, 3} the binary number of 0b010 would mean that we need to include only 2 to the current set.

abcSubset
0000{}
1001{c}
2010{b}
3011{c, b}
4100{a}
5101{a, c}
6110{a, b}
7111{a, b, c}

See bwPowerSet.js file for bitwise solution.

Backtracking Solution

In backtracking approach we’re constantly trying to add next element of the set to the subset, memorizing it and then removing it and try the same with the next element.

See btPowerSet.js file for backtracking solution.

References