可以使用递归的方式来实现多个list集合的排列组合。

具体实现步骤如下:

  1. 定义一个递归函数,该函数接受一个List列表参数,一个当前排列结果列表参数,一个当前处理的List列表索引参数。

  2. 在递归函数中,首先判断当前处理的List列表索引是否超出了List集合的个数,如果是,则说明已经处理完了所有List集合,将当前排列结果列表添加到结果集中。

  3. 如果当前处理的List列表索引没有超出List集合的个数,则遍历该List集合中的所有元素,并将当前元素添加到当前排列结果列表中。

  4. 然后递归调用自身函数,并将当前排列结果列表和下一个List列表的索引作为参数传递进去。

  5. 在递归函数返回后,要将当前排列结果列表中的最后一个元素删除,以便下一次遍历时可以添加新的元素。

示例代码如下:

public static void permutation(List<List<Integer>> lists) {
    List<Integer> result = new ArrayList<>();
    List<List<Integer>> results = new ArrayList<>();
    permutationHelper(lists, result, 0, results);
    // 打印所有排列组合的情况
    for (List<Integer> r : results) {
        System.out.println(r);
    }
}

private static void permutationHelper(List<List<Integer>> lists, List<Integer> result, int index, List<List<Integer>> results) {
    if (index == lists.size()) {
        // 如果处理的List列表索引超出了List集合的个数,说明已经处理完了所有List集合,将当前排列结果添加到结果集中
        results.add(new ArrayList<>(result));
        return;
    }

    // 遍历当前List集合中的所有元素
    for (int i : lists.get(index)) {
        result.add(i);
        permutationHelper(lists, result, index + 1, results);
        result.remove(result.size() - 1);
    }
}

调用示例:

List<Integer> list1 = Arrays.asList(1, 2);
List<Integer> list2 = Arrays.asList(3, 4);
List<Integer> list3 = Arrays.asList(5, 6);
List<List<Integer>> lists = Arrays.asList(list1, list2, list3);
permutation(lists);

输出结果:

[1, 3, 5]
[1, 3, 6]
[1, 4, 5]
[1, 4, 6]
[2, 3, 5]
[2, 3, 6]
[2, 4, 5]
[2, 4, 6]
Java多个list集合如何把所有排列组合的情况列出来

原文地址: https://www.cveoy.top/t/topic/bfjn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录