问题描述
我试图递归地生成列表中的所有项目.我已经看到了一些类似问题的解决方案,但我无法让我的代码工作.有人可以指出我如何修复我的代码吗?
I'm trying to recursively generate all items in a list recursively. I've seen a few solutions to similar questions to this, but I haven't been able to get my code to work. Could someone point out how I can fix my code?
这对所有 S/O'ers 开放,而不仅仅是 Java 人.
This is open to all S/O'ers, not just Java people.
(另外我应该注意到它会因 SO 异常而崩溃).
(Also I should note that it crashes with a SO exception).
样本输入:
[1, 2, 3]
输出:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
//allPossibleItems is an AL of all items
//this is called with generatePerm(null, new ArrayList<Item>);
private void generatePerm(Item i, ArrayList<Item> a) {
if (i != null) { a.add(i); }
if (a.size() == DESIRED_SIZE) {
permutations.add(a);
return;
}
for (int j = 0; j < allPossibleItems.size(); j++) {
if (allPossibleItems.get(j) != i)
generatePerm(allPossibleItems.get(j), a);
}
}
推荐答案
如果 allPossibleItems
包含两个不同的元素,x 和 y,那么您依次将 x 和 y 写入列表,直到到达 DESIRED_SIZE
.这真的是你想要的吗?如果您选择的 DESIRED_SIZE
足够大,您将在堆栈上有太多递归调用,因此出现 SO 异常.
If allPossibleItems
contains two different elements, x and y, then you successively write x and y to the list until it reaches DESIRED_SIZE
. Is that what you really want? If you pick DESIRED_SIZE
sufficiently large, you will have too many recursive calls on the stack, hence the SO exception.
我会做什么(如果原件没有双胞胎/重复项)是:
What I'd do (if original has no douplets / duplicates) is:
public <E> List<List<E>> generatePerm(List<E> original) {
if (original.isEmpty()) {
List<List<E>> result = new ArrayList<>();
result.add(new ArrayList<>());
return result;
}
E firstElement = original.remove(0);
List<List<E>> returnValue = new ArrayList<>();
List<List<E>> permutations = generatePerm(original);
for (List<E> smallerPermutated : permutations) {
for (int index = 0; index <= smallerPermutated.size(); index++) {
List<E> temp = new ArrayList<>(smallerPermutated);
temp.add(index, firstElement);
returnValue.add(temp);
}
}
return returnValue;
}
这篇关于递归生成列表的所有可能排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!