在Java中,实现笛卡尔积的迭代方式有以下几种:
List<List<Integer>> sets = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5, 6)
);
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>());
for (List<Integer> set : sets) {
List<List<Integer>> newResult = new ArrayList<>();
for (List<Integer> list : result) {
for (Integer integer : set) {
List<Integer> newList = new ArrayList<>(list);
newList.add(integer);
newResult.add(newList);
}
}
result = newResult;
}
for (List<Integer> list : result) {
System.out.println(list);
}
public static List<List<Integer>> cartesianProduct(List<List<Integer>> sets, int index) {
List<List<Integer>> result = new ArrayList<>();
if (index == sets.size()) {
result.add(new ArrayList<>());
} else {
for (Integer integer : sets.get(index)) {
for (List<Integer> list : cartesianProduct(sets, index + 1)) {
List<Integer> newList = new ArrayList<>(list);
newList.add(integer);
result.add(newList);
}
}
}
return result;
}
List<List<Integer>> sets = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5, 6)
);
List<List<Integer>> result = cartesianProduct(sets, 0);
for (List<Integer> list : result) {
System.out.println(list);
}
以上是两种常见的实现笛卡尔积的迭代方式,可以根据实际情况选择合适的方式来实现。