поздно для вечеринки, как обычно, но вот пример с объяснением, используя массивы, его легко изменить для списков. Мне нужны все уникальные комбинации нескольких массивов для моего использования в лексикографическом порядке.
Я разместил его, так как ни один из ответов здесь не дает ясного алгоритма, и я не могу выдержать рекурсию. Разве мы не находимся на stackoverflow ?
String[][] combinations = new String[][] {
new String[] { "0", "1" },
new String[] { "0", "1" },
new String[] { "0", "1" },
new String[] { "0", "1" } };
int[] indices = new int[combinations.length];
int currentIndex = indices.length - 1;
outerProcess: while (true) {
for (int i = 0; i < combinations.length; i++) {
System.out.print(combinations[i][indices[i]] + ", ");
}
System.out.println();
while (true) {
// Increase current index
indices[currentIndex]++;
// If index too big, set itself and everything right of it to 0 and move left
if (indices[currentIndex] >= combinations[currentIndex].length) {
for (int j = currentIndex; j < indices.length; j++) {
indices[j] = 0;
}
currentIndex--;
} else {
// If index is allowed, move as far right as possible and process next
// combination
while (currentIndex < indices.length - 1) {
currentIndex++;
}
break;
}
// If we cannot move left anymore, we're finished
if (currentIndex == -1) {
break outerProcess;
}
}
}
Выход;
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111