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

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

    OP's solution moved from the question to an answer:

    Thanks to previous answers, I came up with the following implementation:

    public class OrderedPowerSet {
        private static final int ELEMENT_LIMIT = 12;
        private List inputList;
        public int N;
        private Map>> map = 
                new HashMap>>();
    
        public OrderedPowerSet(List list) {
            inputList = list;
            N = list.size();
            if (N > ELEMENT_LIMIT) {
                throw new RuntimeException(
                        "List with more then " + ELEMENT_LIMIT + " elements is too long...");
            }
        }
    
        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 LinkedHashSet(inputList));
            } else if (elementCount == 1) {
                for (int i = 0 ; i < N ; i++) {
                    LinkedHashSet set = new LinkedHashSet();
                    set.add(inputList.get(i));
                    list.add(set);
                }
            } else {
                list = new ArrayList>();
                for (int i = 0 ; i <= N - elementCount ; i++) {
                    @SuppressWarnings("unchecked")
                    ArrayList subList = (ArrayList)((ArrayList)inputList).clone();
                    for (int j = i ; j >= 0 ; j--) {
                        subList.remove(j);
                    }
                    OrderedPowerSet subPowerSet = 
                            new OrderedPowerSet(subList);
    
                    List> pList = 
                            subPowerSet.getPermutationsList(elementCount-1);
                    for (LinkedHashSet s : pList) {
                        LinkedHashSet set = new LinkedHashSet();
                        set.add(inputList.get(i));
                        set.addAll(s);
                        list.add(set);
                    }               
                }
            }
    
            map.put(elementCount, list);
    
            return map.get(elementCount);
        }
    }
    

提交回复
热议问题