Input: arr[] = [1, 2, 2]
Output: [], [1], [2], [1, 2], [2, 2], [1, 2, 2]
Explanation: The total subsets of given set are - [], [1], [2], [2], [1, 2], [1, 2], [2, 2], [1, 2, 2]
Here [2] and [1, 2] are repeated twice so they are considered only once in the output
Input: arr[] = [1, 2]
Output: [], [1], [2], [1, 2]
Explanation: The total subsets of given set are - [], [1], [2], [1, 2]
The idea is to generate all possible subsets using bitmasking technique where each bit position in a number from 0 to 2^n-1 represents whether to include or exclude the corresponding element from the array. We first sort the array to ensure each subset is sorted when generated. For each number i from 0 to 2^n-1, we check each bit position - if the bit is set, we include the corresponding array element in the current subset. To handle duplicates, we store each generated subset in a set container which automatically eliminates duplicate subsets.
S = [1, 2, 2]
The binary digits from 0 to 7 are
0 --> 000 --> number formed with no set bits --> [ ]
1 --> 001 --> number formed with set bit at position 0 --> [ 1 ]
2 --> 010 --> number formed with set bit at position 1 --> [ 2 ]
3 --> 011 --> number formed with set bit at position 0 and 1 --> [ 1 , 2 ]
4 --> 100 --> number formed with set bit at position 2 --> [ 2 ]
5 --> 101 --> number formed with set bit at position 0 and 2 --> [ 1 , 2]
6 --> 110 --> number formed with set bit at position 1 and 2 --> [ 2 , 2]
7 --> 111 --> number formed with set bit at position 0 , 1 and 2 --> [1 , 2 , 2]
After removing duplicates final result will be [ ], [ 1 ], [ 2 ], [ 1 , 2 ], [ 2 , 2 ], [ 1 , 2 , 2]