温馨提示×

java多个数组排列组合

小亿
87
2024-01-05 17:49:48
栏目: 编程语言

要实现多个数组的排列组合,可以使用递归的方法。具体步骤如下:

  1. 创建一个递归函数,接收三个参数:原始数组集合、当前排列结果、当前处理的数组索引。
  2. 在递归函数中,首先检查当前处理的数组索引是否超出了原始数组集合的长度,如果超出了则将当前排列结果加入到最终结果集合中。
  3. 如果当前处理的数组索引没有超出原始数组集合的长度,则获取当前处理的数组,遍历该数组中的所有元素,并将每个元素添加到当前排列结果中。
  4. 调用递归函数自身,将当前排列结果和下一个数组索引作为参数。
  5. 在递归函数结束后,返回最终结果集合。

下面是一个示例代码:

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]

以上代码实现了三个数组的排列组合,你可以根据需要修改原始数组集合,实现任意数量的数组排列组合。

0