Power Set:
The power set (or powerset) of any set S is the set of all subsets of S, including the empty set and S itself.
Solution:
- Recursive Algorithm: A Power set of P(n) can be computer from P(n-1) by added nth element in each set of P(n-1)
- Iterative Algorithm: Based on binary representation
Recursive Algorithm:
- If
index == set.size
then- Create setsOfSet
- Add empty set to setsOfSet1
- Else
- Recursively call with index + 1
- get ithElement from Set
- Create empty setsOfSet2
- Iterate all sets S for setsOfSet1
- Create newSet
- Add elements of set S to newSet
- Add ithElement to newSet
- Add newSet to setsOfSet2
- Add all sets setsOfSet2 to setsOfSet1
- Return setsOfSet1
Iterative Algorithm:
- Compute totalNumberSubset i.e 2^set.size
- Iterate 0 to totalNumberSubset
- Covert each number to binary representation
- Create subset based on binary representation
Latest Source Code:
Github: PowerSet.java
Output:
Power of [1, 3, 2] (Recursive): [[], [2], [3], [2, 3], [1], [2, 1], [3, 1], [2, 3, 1]] Power of [1, 3, 2] (Iterative): [[], [1], [3], [1, 3], [2], [1, 2], [3, 2], [1, 3, 2]]