計算笛卡爾積的泛型方法
阿新 • • 發佈:2018-12-15
private <T> List<List<T>> cartesianProduct(List<List<T>> lists) { List<List<T>> resultLists = new ArrayList<>(); if (lists.size() == 0) { resultLists.add(new ArrayList<>()); return resultLists; } else { List<T> firstList = lists.get(0); List<List<T>> remainingLists = cartesianProduct(lists.subList(1, lists.size())); for (T condition : firstList) { for (List<T> remainingList : remainingLists) { ArrayList<T> resultList = new ArrayList<>(); resultList.add(condition); resultList.addAll(remainingList); resultLists.add(resultList); } } } return resultLists; }
說明:先將要計算的笛卡爾積集合一起放到一個大集合中。