在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);
}
以上是兩種常見的實現笛卡爾積的迭代方式,可以根據實際情況選擇合適的方式來實現。