How to generate the power-set of a given List?

后端 未结 8 1551
南方客
南方客 2020-11-29 05:58

I\'m trying to generate a collection of all 2^N - 1 possible combinations of a given List of length N. The collection will map the number of elements in a combination to an

8条回答
  •  独厮守ぢ
    2020-11-29 06:42

    static Map>> powerset = new HashMap<>();
    
    public static void main(String[] args) throws IOException {
        powerset(Arrays.asList(1, 2, 3));
        for (Integer key : powerset.keySet()) {
            System.out.print(key + " -> ");
            System.out.println(Arrays.toString(powerset.get(key).toArray()));
        }
    }
    
    static void powerset(List src) {
        powerset(new LinkedList<>(), src);
    }
    
    private static void powerset(LinkedList prefix, List src) {
        if (src.size() > 0) {
            prefix = new LinkedList<>(prefix); //create a copy to not modify the orig
            src = new LinkedList<>(src); //copy
            Integer curr = src.remove(0);
            collectResult(prefix, curr);
            powerset(prefix, src);
            prefix.add(curr);
            powerset(prefix, src);
        }
    }
    
    private static void collectResult(LinkedList prefix, Integer curr) {
        prefix = new LinkedList<>(prefix); //copy
        prefix.add(curr);
        List> addTo;
        if (powerset.get(prefix.size()) == null) {
            List> newList = new LinkedList<>();
            addTo = newList;
        } else {
            addTo = powerset.get(prefix.size());
        }
        addTo.add(prefix);
        powerset.put(prefix.size(), addTo);
    }
    

    OUTPUT

    1 -> [[1], [2], [3]]
    2 -> [[2, 3], [1, 2], [1, 3]]
    3 -> [[1, 2, 3]]
    

提交回复
热议问题