生成所有可能的组合-Java [英] Generate All Possible Combinations - Java
问题描述
我有一个项目{a,b,c,d}的列表,当我需要生成所有可能的组合时,
I have a list of items {a,b,c,d} and I need to generate all possible combinations when,
- 您可以选择任意数量的项目
- 顺序不重要(ab = ba)
- 不考虑空集
如果我们抓住可能性,应该是
If we take the possibilities, it should be,
n=4, number of items
total #of combinations = 4C4 + 4C3 + 4C2 + 4C1 = 15
我使用了以下递归方法:
I used the following recursive method:
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)组合。
Consider the combination as a binary sequence, if all the 4 are present, we get 1111 , if the first alphabet is missing then we get 0111, and so on.So for n alphabets we'll have 2^n -1 (since 0 is not included) combinations.
现在,在生成的二进制序列中,如果代码为1,则该元素存在,否则不包括在内。下面是概念验证的实现:
Now, in your binary sequence produced, if the code is 1 , then the element is present otherwise it is not included. Below is the proof-of-concept implementation:
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();
}
这是可重复使用的通用实现:
And here's a generic reusable implementation:
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);
}
这篇关于生成所有可能的组合-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!