生成所有可能的组合-Java


问题内容

我有一个项目{a,b,c,d}的列表,当我需要生成所有可能的组合时,

  • 您可以选择任意数量的项目
  • 顺序不重要(ab = ba)
  • 空集不被考虑

如果我们抓住可能性,那就应该是

n=4, number of items
total #of combinations = 4C4 + 4C3 + 4C2 + 4C1 = 15

我使用了以下递归方法:

private void countAllCombinations (String input,int idx, String[] options) {
    for(int i = idx ; i < options.length; i++) {
        String output = input + "_" + options[i];
        System.out.println(output);
        countAllCombinations(output,++idx, options);
    }
}

public static void main(String[] args) {
    String arr[] = {"A","B","C","D"};
    for (int i=0;i<arr.length;i++) {
        countAllCombinations(arr[i], i, arr);
    }
}

当数组大时,有没有更有效的方法?


问题答案:

将组合视为一个二进制序列,如果所有4个都存在,则得到1111,如果缺少第一个字母,则得到0111,依此类推。对于n个字母,我们将得到2 ^ n
-1(从0开始不包括在内)组合。

现在,在生成的二进制序列中,如果代码为1,则该元素存在,否则不包括在内。以下是概念验证的实现:

String arr[] = { "A", "B", "C", "D" };
int n = arr.length;
int N = (int) Math.pow(2d, Double.valueOf(n));  
for (int i = 1; i < N; i++) {
    String code = Integer.toBinaryString(N | i).substring(1);
    for (int j = 0; j < n; j++) {
        if (code.charAt(j) == '1') {
            System.out.print(arr[j]);
        }
    }
    System.out.println();
}

这是一个通用的可重用实现:

public static <T> Stream<List<T>> combinations(T[] arr) {
    final long N = (long) Math.pow(2, arr.length);
    return StreamSupport.stream(new AbstractSpliterator<List<T>>(N, Spliterator.SIZED) {
        long i = 1;
        @Override
        public boolean tryAdvance(Consumer<? super List<T>> action) {
            if(i < N) {
                List<T> out = new ArrayList<T>(Long.bitCount(i));
                for (int bit = 0; bit < arr.length; bit++) {
                    if((i & (1<<bit)) != 0) {
                        out.add(arr[bit]);
                    }
                }
                action.accept(out);
                ++i;
                return true;
            }
            else {
                return false;
            }
        }
    }, false);
}