Algorithm:
The total number of possible subset a set can have is 2^n, where n is the number of elements in the set.
We can generate all possible subset using binary counter.
Consider a set 'A' having elements {a, b, c}. So we will generate binary number upto 2^n - 1 (as we will include 0 also).
Binary counter | subset formed | Explanation |
---|---|---|
000 | { } | as all bits are unset , so exclude all |
001 | { a } | as only 1st bit is set , we will include only 1st element from the set i.e 'a' |
010 | { b } | as only 2nd bit is set , we will include only 2nd element from the set i.e 'b' |
011 | { a ,b } | as 1st and 2nd bits are set , we will include 1st and 2nd element from the set i.e 'a' and 'b' |
100 | { c } | as only 3rd bit is set , we will include 3rd element from the set i.e 'c' |
101 | { a ,c } | as 1st and 3rd bits are set , we will include 1st and 3rd element from the set i.e 'a' and 'c' |
110 | { b, c } | as 2nd and 3rd bits are set , we will include 2nd and 3rd element from the set i.e 'b' and 'c' |
111 | { a , b, c } | all bits are set , include all elements from the set. |
Comments