【发布时间】:2012-05-17 12:15:32
【问题描述】:
假设我们给出了一些项目的列表,比如字符串。
list 1: "a", "b", "c"
list 2: "d", "e", "f"
list 3: "1", "2", "3"
results: (a, d, 1), (a, d, 2), ... (c, f, 3)
(实际用例与字符串等无关,这只是一个模型)
我写了一个递归方法来做它,但我对它不满意,因为它创建了很多被扔掉的临时集(是的,我知道在 java 中创建对象很便宜,通常 cpu 指令比 malloc 在C(来源:Java Concurrency in Action,p241),eden GC 很便宜,等等等等。幽默我:)。
void combine(List<List<String>> itemLists, List<Set<String>> combinations, Set<String> partial) {
if (itemLists == null || itemLists.isEmpty()) return;
List<String> items = itemLists.get(0);
for (String s : items) {
Set<String> tmpSet = new HashSet<>(partial);
tmpSet.add(s);
if (itemLists.size() == 0) //termination test
combinations.add(tmpSet);
else
combine(itemLists.subList(1, itemLists.size()), combinations, tmpSet);
}
}
那么,你会怎么做呢?
edit:明确地说,我不想创建排列。我想创建 sizeof(list of lists) 大的集合。
【问题讨论】:
-
嗯,你可以循环执行...(不需要递归)。
-
列表是否包含相同数量的元素?
-
您想将所有集合保存在内存中吗?或者您正在搜索结果集中的特定组合或属性?
-
@Paul Vargas - 这不是我想要的。查看我的编辑并查看我的代码。
-
Here is a short answer, here a longer one with Iterator and Iterable。关键字是“笛卡尔积”,什么是最有效的?就大小而言,我想,既然您谈论 GC?还是速度?
标签: java algorithm collections cartesian-product