Printing all possible subsets of a list

后端 未结 7 1371
半阙折子戏
半阙折子戏 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 12:12

    Peter Minchev's solution modified to handle larger lists through BigInteger

    public static List> getAllSubsets(List input) {
        BigInteger allMasks = BigInteger.ONE.shiftLeft(input.size());
        List> output = new ArrayList<>();
        for(BigInteger i=BigInteger.ZERO;allMasks.subtract(i).compareTo(BigInteger.ZERO)>0; i=i.add(BigInteger.ONE)) {
            List subList = new ArrayList();
            for(int j=0;j 0) {
                    subList.add(input.get(j));
                }
            }
            System.out.println(subList);
            output.add(subList);
        }
        return output;
    }
    

提交回复
热议问题