Obtaining a powerset of a set in Java

后端 未结 26 2112
青春惊慌失措
青春惊慌失措 2020-11-22 11:33

The powerset of {1, 2, 3} is:

{{}, {2}, {3}, {2, 3}, {1, 2}, {1, 3}, {1, 2, 3}, {1}}

Let\'s say I have a Set in Java:<

26条回答
  •  一生所求
    2020-11-22 11:50

    // input: S
    // output: P
    // S = [1,2]
    // P = [], [1], [2], [1,2]
    
    public static void main(String[] args) {
        String input = args[0];
        String[] S = input.split(",");
        String[] P = getPowerSet(S);
        if (P.length == Math.pow(2, S.length)) {
            for (String s : P) {
                System.out.print("[" + s + "],");
            }
        } else {
            System.out.println("Results are incorrect");
        }
    }
    
    private static String[] getPowerSet(String[] s) {
        if (s.length == 1) {
            return new String[] { "", s[0] };
        } else {
            String[] subP1 = getPowerSet(Arrays.copyOfRange(s, 1, s.length));
            String[] subP2 = new String[subP1.length];
            for (int i = 0; i < subP1.length; i++) {
                subP2[i] = s[0] + subP1[i];
            }
            String[] P = new String[subP1.length + subP2.length];
            System.arraycopy(subP1, 0, P, 0, subP1.length);
            System.arraycopy(subP2, 0, P, subP1.length, subP2.length);
            return P;
        }
    
    }
    

提交回复
热议问题