Java排列组合之全排列算法

public class Main {

    public static void main(String[] args) {

        String a[] = {"a", "b", "c", "d"};

        int l = a.length;

        int nBit = 1 << l;

        int total = 0;

        StringBuilder sb;
        for (int i = 1; i <= nBit; i++) {
            sb = new StringBuilder();
            for (int j = 0; j < l; j++) {
                if ((i << (31 - j)) >> 31 == -1) {
                    sb.append(", ").append(a[j]);
                }
            }
            if (sb.length() > 0) {
                total++;
                System.out.println(sb.deleteCharAt(0).toString());
            }
        }
        System.out.println("共有" + total + "种组合方式");
    }
}

输出示例:

 a
 b
 a, b
 c
 a, c
 b, c
 a, b, c
 d
 a, d
 b, d
 a, b, d
 c, d
 a, c, d
 b, c, d
 a, b, c, d
共有15种组合方式