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

后端 未结 8 1560
南方客
南方客 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 getCombinationsLists(List elements)
    {
        
        //return list with empty String
        if(elements.size() == 0){
            List allLists = new ArrayList();
            allLists.add("");
            return allLists ;
        }
    
        String first_ele = elements.remove(0);
        List 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.

提交回复
热议问题