Java

java多个list排列组合的方法是什么

小亿
131
2023-12-16 01:21:37
栏目: 编程语言

在Java中,可以使用递归来实现多个List的排列组合。

以下是一个示例代码,用于实现两个List的排列组合:

import java.util.ArrayList;
import java.util.List;

public class Combination {

    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);

        List<Integer> list2 = new ArrayList<>();
        list2.add(4);
        list2.add(5);

        List<List<Integer>> result = combination(list1, list2);
        for (List<Integer> combination : result) {
            System.out.println(combination);
        }
    }

    public static List<List<Integer>> combination(List<Integer> list1, List<Integer> list2) {
        List<List<Integer>> result = new ArrayList<>();

        if (list1.isEmpty()) {
            result.add(new ArrayList<>(list2));
            return result;
        }

        if (list2.isEmpty()) {
            result.add(new ArrayList<>(list1));
            return result;
        }

        int firstElement = list1.get(0);
        List<Integer> restOfList1 = list1.subList(1, list1.size());

        List<List<Integer>> combinationsWithoutFirstElement = combination(restOfList1, list2);
        for (List<Integer> combination : combinationsWithoutFirstElement) {
            List<Integer> newCombination = new ArrayList<>();
            newCombination.add(firstElement);
            newCombination.addAll(combination);
            result.add(newCombination);
        }

        List<Integer> restOfList2 = list2.subList(1, list2.size());
        List<List<Integer>> combinationsWithoutFirstElementInList2 = combination(list1, restOfList2);
        result.addAll(combinationsWithoutFirstElementInList2);

        return result;
    }
}

在以上代码中,我们首先定义了两个List:list1和list2。然后,我们调用combination方法对这两个List进行排列组合,并将结果保存在一个List<List>中。最后,我们遍历结果列表,并打印出每一组排列组合。

请注意,此代码中的combination方法使用递归来实现排列组合。它首先检查两个列表中是否有一个为空,如果是,则将另一个列表的元素添加到结果列表中,并返回结果。否则,它取出列表中的第一个元素,将其与递归调用返回的每个排列组合进行组合,并将结果添加到结果列表中。

在实际应用中,您可以根据需要修改combination方法,以处理任意数量的列表。

0
看了该问题的人还看了