要實現多個數組的排列組合,可以使用遞歸的方法。具體步驟如下:
下面是一個示例代碼:
import java.util.ArrayList;
import java.util.List;
public class ArrayPermutation {
public static List<List<Integer>> permute(int[][] arrays) {
List<List<Integer>> result = new ArrayList<>();
permuteHelper(result, new ArrayList<>(), arrays, 0);
return result;
}
private static void permuteHelper(List<List<Integer>> result, List<Integer> current, int[][] arrays, int index) {
if (index >= arrays.length) {
result.add(new ArrayList<>(current));
return;
}
int[] array = arrays[index];
for (int i = 0; i < array.length; i++) {
current.add(array[i]);
permuteHelper(result, current, arrays, index + 1);
current.remove(current.size() - 1);
}
}
public static void main(String[] args) {
int[][] arrays = {
{1, 2, 3},
{4, 5},
{6, 7, 8}
};
List<List<Integer>> result = permute(arrays);
for (List<Integer> list : result) {
System.out.println(list);
}
}
}
輸出結果為:
[1, 4, 6]
[1, 4, 7]
[1, 4, 8]
[1, 5, 6]
[1, 5, 7]
[1, 5, 8]
[2, 4, 6]
[2, 4, 7]
[2, 4, 8]
[2, 5, 6]
[2, 5, 7]
[2, 5, 8]
[3, 4, 6]
[3, 4, 7]
[3, 4, 8]
[3, 5, 6]
[3, 5, 7]
[3, 5, 8]
以上代碼實現了三個數組的排列組合,你可以根據需要修改原始數組集合,實現任意數量的數組排列組合。