dimanche 16 juillet 2017

Finding all possible subsets of array elements

Finding all possible subset of array elements

    int a[4] = { 1,2,3,4};  
    vector< vector<int> > subset;  
    vector<int> empty;
    subset.push_back( empty );

    for (int i = 0; i < 4; i++)
    {
        vector< vector<int> > subsetTemp = subset;

        for (int j = 0; j < subsetTemp.size(); j++)
             subsetTemp[j].push_back( a[i] );


        for (int j = 0; j < subsetTemp.size(); j++)
            subset.push_back( subsetTemp[j] );
    }

When I try to understand this code I am creating subset in my mind this way :

 subset  0 -> 1 2 3 4      
         1 -> 2 3 4     
         2 -> 3 4       
         3 -> 4        

So when I will print this vector it will give wrong output.
Actual output is this :

    ( empty)      
1      
2      
1 2       
3      
1 3       
2 3       
1 2 3      
4      
1 4     
2 4     
...     
...      

How the empty set is getting printed , how 1 2 is getting printed ?? I am confused.
( First few entries in subset vector are enough to understand. )

Aucun commentaire:

Enregistrer un commentaire