温馨提示×

Java笛卡尔积的递归实现方式是什么

小樊
87
2024-08-11 00:51:38
栏目: 编程语言

在Java中实现笛卡尔积的递归方式可以通过一个递归函数来实现。下面是一个简单的例子:

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

public class CartesianProduct {
    public static List<List<Integer>> cartesianProduct(List<List<Integer>> lists) {
        List<List<Integer>> result = new ArrayList<>();
        cartesianProductHelper(lists, result, 0, new ArrayList<>());
        return result;
    }

    private static void cartesianProductHelper(List<List<Integer>> lists, List<List<Integer>> result, int index, List<Integer> current) {
        if (index == lists.size()) {
            result.add(new ArrayList<>(current));
            return;
        }

        for (int i = 0; i < lists.get(index).size(); i++) {
            current.add(lists.get(index).get(i));
            cartesianProductHelper(lists, result, index + 1, current);
            current.remove(current.size() - 1);
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> lists = new ArrayList<>();
        lists.add(List.of(1, 2));
        lists.add(List.of(3, 4));
        lists.add(List.of(5, 6));

        List<List<Integer>> result = cartesianProduct(lists);

        for (List<Integer> tuple : result) {
            System.out.println(tuple);
        }
    }
}

在上面的代码中,cartesianProduct函数接受一个包含多个列表的列表作为输入,然后调用cartesianProductHelper函数进行递归计算笛卡尔积。在cartesianProductHelper函数中,我们首先检查当前索引是否等于列表的大小,如果是则将当前结果添加到最终结果中。否则,我们遍历当前列表中的元素,并递归调用cartesianProductHelper函数来计算下一个列表的笛卡尔积。

0