Printing all possible subsets of a list

后端 未结 7 1271
半阙折子戏
半阙折子戏 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<List<Integer>> getAllSubsets(List<Integer> input) {
        BigInteger allMasks = BigInteger.ONE.shiftLeft(input.size());
        List<List<Integer>> output = new ArrayList<>();
        for(BigInteger i=BigInteger.ZERO;allMasks.subtract(i).compareTo(BigInteger.ZERO)>0; i=i.add(BigInteger.ONE)) {
            List<Integer> subList = new ArrayList<Integer>();
            for(int j=0;j<input.size();j++) {
                if(i.and(BigInteger.valueOf(1<<j)).compareTo(BigInteger.ZERO) > 0) {
                    subList.add(input.get(j));
                }
            }
            System.out.println(subList);
            output.add(subList);
        }
        return output;
    }
    
    0 讨论(0)
提交回复
热议问题