Find all distinct subsets of a given set using BitMasking Approach | C ++ program to find all subsets of given set . Any repeated subset is considered only once in the output ; Utility function to split the string using a delim . Refer - http : stackoverflow . com / questions / 236129 / split - a - string - in - c ; Function to find all subsets of given set . Any repeated subset is considered only once in the output ; Run counter i from 000. . 0 to 111. . 1 ; consider each element in the set ; Check if jth bit in the i is set . If the bit is set , we consider jth element from set ; if subset is encountered for the first time If we use set < string > , we can directly insert ; consider every subset ; split the subset and print its elements ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < string > split ( const string & s , char delim ) { vector < string > elems ; stringstream ss ( s ) ; string item ; while ( getline ( ss , item , delim ) ) elems . push_back ( item ) ; return elems ; } int printPowerSet ( int arr [ ] , int n ) { vector < string > list ; for ( int i = 0 ; i < ( int ) pow ( 2 , n ) ; i ++ ) { string subset = " " ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & ( 1 << j ) ) != 0 ) subset += to_string ( arr [ j ] ) + " | " ; } if ( find ( list . begin ( ) , list . end ( ) , subset ) == list . end ( ) ) list . push_back ( subset ) ; } for ( string subset : list ) { vector < string > arr = split ( subset , ' ▁ ' ) ; for ( string str : arr ) cout << str << " ▁ " ; cout << endl ; } } int main ( ) { int arr [ ] = { 10 , 12 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printPowerSet ( arr , n ) ; return 0 ; }