【发布时间】:2020-07-16 16:21:45
【问题描述】:
我正在尝试从大小为 N 的列表中获取大小为 K 的所有可能组合。
我有一个带有“人类”对象的列表,我正在尝试创建一个新的 ArrayList,它将用列表对象填充。每个列表都是“人类”对象的不同组合。
一个简单的数字示例是:从一个包含 1,2,3 的列表中,我想得到一个 ArrayList,它看起来像这样:[[1,2], [1,3], [2,3]]
我也不介意它看起来像这样:[[1], [2], [3], [1,2], [1,3], [2,3]]
这是我的代码:
public void combination(List<Human> people, int k, ArrayList<List> result) {
if (people.size() < k) {
return;
}
if (k == 1) {
for (Human hum : people) {
List<Human> combinations = new ArrayList<Human>();
combinations.add(hum);
result.add(combinations);
}
}
else if (people.size() == k) {
List<Human> combinations = new ArrayList<Human>();
for (Human hum : people) {
combinations.add(hum);
}
result.add(combinations);
}
else if (people.size() > k) {
for (int i = 0; i < people.size(); i++) {
List<Human> combinations = new ArrayList<Human>();
combinations.add(people.get(i));
result.add(combinations);
combination(people.subList(i + 1, people.size()), k - 1, result);
}
}
}
我使用本站最后一种方法作为参考:https://hmkcode.com/calculate-find-all-possible-combinations-of-an-array-using-java/
目前我在新的 ArrayList 中获得了正确数量的结果,但里面的每个 List 只包含一个 Human。
我高度怀疑问题出在最后一个else if,因为我很难理解递归。
请随时提出任何问题或为此提出任何其他实施建议。
【问题讨论】:
-
除了 else if 之外的所有内容都是快速跳过最后一个
for循环的代码。在最后一个for循环中,为每个人创建了一个组合,并且只添加了一个人,所以当然每个组合中只有一个人。我认为列表中的每个人都是独一无二的? -
@MaartenBodewes 感谢您的回复,这就是我的想法,但是我无法弄清楚如何修改“结果”以获得我需要的东西
-
也许你错过了我评论中的问题?列表中没有骗子?
-
@MaartenBodewes 是的,抱歉,列表中的每个人都是独一无二的,是的,没有骗子
-
这不是已经在最后一个循环中发生了吗,我用较小的“k”和较小的人员列表递归调用它?
标签: java arrays list combinations