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

后端 未结 8 1496
南方客
南方客 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:41
    public static List<String> getCombinationsLists(List<String> elements)
    {
        
        //return list with empty String
        if(elements.size() == 0){
            List<String> allLists = new ArrayList<String>();
            allLists.add("");
            return allLists ;
        }
    
        String first_ele = elements.remove(0);
        List<String> rest = getCombinationsLists(elements);
        int restsize = rest.size();
        //Mapping the first_ele with each of the rest of the elements.
        for (int i = 0; i < restsize; i++) {
            String ele = first_ele + rest.get(i);
            rest.add(ele);
        }
       
        return   rest;
    }
    

    This Power set is one of the exercise in the book SICP "Structure and Interpretation of Computer Programming".Every Programmer should read it.

    0 讨论(0)
  • 2020-11-29 06:42
    static Map<Integer, List<LinkedList<Integer>>> 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<Integer> src) {
        powerset(new LinkedList<>(), src);
    }
    
    private static void powerset(LinkedList<Integer> prefix, List<Integer> 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<Integer> prefix, Integer curr) {
        prefix = new LinkedList<>(prefix); //copy
        prefix.add(curr);
        List<LinkedList<Integer>> addTo;
        if (powerset.get(prefix.size()) == null) {
            List<LinkedList<Integer>> 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]]
    
    0 讨论(0)
提交回复
热议问题