【发布时间】:2012-12-17 14:51:20
【问题描述】:
基本上,我有一个包含 25 个不同人的数组,我需要选择其中的 5 个人,并尽可能地组合每一个组合,而不是使用同一个人的重复。
我能想到的唯一合乎逻辑的方法是使用 5 个 for 循环并检查 person 是否已被使用,尽管这似乎可能有更好的递归方法。
如果有人能提供帮助,我将不胜感激。
这是我的课的一个例子;
public class Calculator {
final Person[] people = new Person[25]; //Pretend we have filled in this info already
public List<Group> generateList()
{
final List<Group> possible = new ArrayList<>();
for (int a = 0; a < 25; a++)
{
for (int b = 0; b < 25; b++)
{
for (int c = 0; c < 25; c++)
{
for (int d = 0; d < 25; d++)
{
for (int e = 0; e < 25; e++)
{
final Group next = new Group();
next.set = new Person[] {
people[a],
people[b],
people[c],
people[d],
people[e]
};
possible.add(next);
}
}
}
}
}
return possible;
}
class Group {
Person[] set = new Person[5];
}
class Person {
String name;
int age;
}
}
但是,我不确定执行此操作的最佳方法以及是否可以得到所有组合。我也知道这里没有重复检查,我会通过检查来做到这一点;
如果(b == a)继续;
等等
我将不胜感激。
【问题讨论】:
-
对我来说就像家庭作业。还有一个重复
-
更好的链接:使用递归很有可能。另一种方法是使用binary combinations的属性
标签: java recursion combinations