问题描述
我有一个对象的arraylist,我想创建所有可能的组合(根据一组简单的规则)。存储在列表中的每个对象都包含一个squadNumber和一个字符串。以下是我存储的典型列表示例:
I have an arraylist of objects that I want to create all possible combinations (according to a simple set of rules). Each object that is stored in the list holds a squadNumber and a string. Here is an example of a typical list I am storing:
0: 1, A
1: 1, B
2: 2, A
3: 2, B
4: 3, C
5: 3, D
6: 4, C
7: 4, D
我想获得每个squadNumber只能出现一次的所有组合,例如:(1,A),(2,A),(3,C),(4,C)那么下一个组合将是(1,A),(2,A),(3,C),( 4,d)。
我如何在java中解决这个问题?通常我会使用嵌套循环,但它全部存储在一个列表中这一事实使我感到困惑。
I want to get all the combinations where each squadNumber can only be present once, for example: (1,A),(2,A),(3,C),(4,C) then the next combination would be (1,A),(2,A),(3,C),(4,D).How would I go about this in java? Usually I would use a nested loop, but the fact that it's all being stored in one list complicates things for me.
谢谢,
paintstripper
Thanks,paintstripper
推荐答案
已编辑
算法如下:
- 按数字拆分所有小队。所以我们有小队的名单为1,
小队2的另一个名单等等。 - 运行dfs。在第n步,我们添加第n个小队。
代码
// Split squads by numbers, so we can iterate through each number independently.
private Map<Integer, List<Squad>> splitSquadsByNumbers(List<Squad> squads) {
Map<Integer, List<Squad>> res = new HashMap<Integer, List<Squad>>();
for (Squad squad : squads) {
if (res.get(squad.getNumber()) == null) {
res.put(squad.getNumber(), new ArrayList<Squad>());
}
res.get(squad.getNumber()).add(squad);
}
return res;
}
List<Integer> squadNumbers;
Map<Integer, List<Squad>> squadsByNumbers;
Stack<Squad> stack;
// Iterating through each squad with number squadNumbers[position] and try to add to stack, at the end pop it from stack.
private void dfs(int position) {
if (position == squadNumber.size()) {
System.out.println(stack.toString());
} else {
for (Squad squad : squadsByNumbers.get(squadNumber.get(position))) {
stack.push(squad);
dfs(position + 1);
stack.pop();
}
}
}
private void main(List<Squad> squads) {
squadsByNumbers = splitSquadsByNumbers(squads);
squadNumber = new ArrayList(squadsByNumber.keySet());
Collections.sort(squadNumbers);
stack = new Stack<Squad>();
dfs(0);
}
这篇关于列表的可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!