Obtaining a powerset of a set in Java

后端 未结 26 1686
青春惊慌失措
青春惊慌失措 2020-11-22 11:33

The powerset of {1, 2, 3} is:

{{}, {2}, {3}, {2, 3}, {1, 2}, {1, 3}, {1, 2, 3}, {1}}

Let\'s say I have a Set in Java:<

26条回答
  •  伪装坚强ぢ
    2020-11-22 11:46

    If n < 63, which is a reasonable assumption since you'd run out of memory (unless using an iterator implementation) trying to construct the power set anyway, this is a more concise way to do it. Binary operations are way faster than Math.pow() and arrays for masks, but somehow Java users are afraid of them...

    List list = new ArrayList(originalSet);
    int n = list.size();
    
    Set> powerSet = new HashSet>();
    
    for( long i = 0; i < (1 << n); i++) {
        Set element = new HashSet();
        for( int j = 0; j < n; j++ )
            if( (i >> j) % 2 == 1 ) element.add(list.get(j));
        powerSet.add(element); 
    }
    
    return powerSet;
    

提交回复
热议问题