How to find all the subsets of an array in java? [

2019-09-22 13:11发布

This question already has an answer here:

I need to find all the subsets of an array using java.For e.g. if we have a set {1,2,3} then i should get {},{1},{2},{3},{1,2},{2,3},{1.3},{1,2,3}

1条回答
男人必须洒脱
2楼-- · 2019-09-22 13:40

You can do this to avoid needing to recurse the solutions.

public static <T> void printCombinations(T[] arr) {
    for(long i = 0, max = 1L << arr.length; i < max; i++) {
        Set<T> ts = new HashSet<>();
        for(int j = 0; j < arr.length; j++) {
            if ((i >> j) != 0)
                ts.add(list.get(j));
        }
        System.out.println(ts);
    }
}
查看更多
登录 后发表回答