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

怎甘沉沦 提交于 2019-12-14 03:33:59

问题


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:


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);
    }
}


来源:https://stackoverflow.com/questions/29919846/how-to-find-all-the-subsets-of-an-array-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!