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

后端 未结 8 1613
南方客
南方客 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:28

    I test the code proposed by Elist and I found errors.

    Here is a proposed correction : (in the last else of the function getPermutation(), I made two changes)

    public class OrderedPowerSet {
    private ArrayList inputList;
    public int N;
    private Map>> map = 
            new HashMap>>();
    
    public OrderedPowerSet(ArrayList list) {
        inputList = list;
        N = list.size();
    }
    
    public List> getPermutationsList(int elementCount) {
        if (elementCount < 1 || elementCount > N) {
            throw new IndexOutOfBoundsException(
                    "Can only generate permutations for a count between 1 to " + N);
        }
        if (map.containsKey(elementCount)) {
            return map.get(elementCount);
        }
    
        ArrayList> list = new ArrayList>();
    
        if (elementCount == N) {
            list.add(new HashSet(inputList));
        } else if (elementCount == 1) {
            for (int i = 0 ; i < N ; i++) {
                Set set = new HashSet();
                set.add(inputList.get(i));
                list.add(set);
            }
        } else {
            for (int i = 0 ; i < N-elementCount ; i++) {
                @SuppressWarnings("unchecked")
                ArrayList subList = (ArrayList)inputList.clone(); // one change
                subList.remove(0);
                OrderedPowerSet subPowerSet = 
                        new OrderedPowerSet(subList);
                for (Set s : subPowerSet.getPermutationsList(elementCount-1)) {
                    Set set = new HashSet();
                    set.add(inputList.get(i));
                    set.addAll(s);
                    list.add(set); // second change
                }
    
            }
        }
    
        map.put(elementCount, list);
    
        return map.get(elementCount);
    }
    

    }

提交回复
热议问题