Printing all possible subsets of a list

后端 未结 7 1354
半阙折子戏
半阙折子戏 2020-12-28 11:18

I have a List of elements (1, 2, 3), and I need to get the superset (powerset) of that list (without repeating elements). So basically I need to create a List of Lists that

7条回答
  •  旧巷少年郎
    2020-12-28 11:53

    I've noticed that answers are focused on the String list. Consequently, I decided to share more generic answer. Hope it'll be fouund helpful. (Soultion is based on another solutions I found, I combined it to a generic algorithem.)

    /**
     * metod returns all the sublists of a given list
     * the method assumes all object are different
     * no matter the type of the list (generics)
     * @param list the list to return all the sublist of
     * @param 
     * @return list of the different sublists that can be made from the list object
     */
    public static   List>getAllSubLists(Listlist)
    {
        ListsubList;
        List>res = new ArrayList<>();
        List> indexes = allSubListIndexes(list.size());
        for(List subListIndexes:indexes)
        {
            subList=new ArrayList<>();
            for(int index:subListIndexes)
                subList.add(list.get(index));
            res.add(subList);
        }
        return res;
    }
    /**
     * method returns list of list of integers representing the indexes of all the sublists in a N size list
     * @param n the size of the list
     * @return list of list of integers of indexes of the sublist
     */
    public static List> allSubListIndexes(int n) {
        List> res = new ArrayList<>();
        int allMasks = (1 << n);
        for (int i = 1; i < allMasks; i++)
        {
            res.add(new ArrayList<>());
            for (int j = 0; j < n; j++)
                if ((i & (1 << j)) > 0)
                    res.get(i-1).add(j);
    
        }
        return res;
    }
    

提交回复
热议问题