Obtaining a powerset of a set in Java

后端 未结 26 1735
青春惊慌失措
青春惊慌失措 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:52

    We could write the power set with or without using recursion. Here is an attempt without recursion:

    public List> getPowerSet(List set) {
        List> powerSet = new ArrayList>();
        int max = 1 << set.size();
        for(int i=0; i < max; i++) {
            List subSet = getSubSet(i, set);
            powerSet.add(subSet);
        }
        return powerSet;
    }
    
    private List getSubSet(int p, List set) {
        List subSet = new ArrayList();
        int position = 0;
        for(int i=p; i > 0; i >>= 1) {
            if((i & 1) == 1) {
                subSet.add(set.get(position));
            }
            position++;
        }
        return subSet;
    }
    

提交回复
热议问题