我想递归生成列表中的所有项目递归。我已经看到了一些解决方案,以类似的问题,但我一直没能得到我的code工作。可能有人指出,如何可以解决我的code?
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]
Sample input: [1, 2, 3]
输出: [1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1]
Output: [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 a 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.
我会做(如果原来没有douplets):
What I'd do (if original has no douplets):
public List<List<E>> generatePerm(List<E> original) {
if (original.size() == 0) {
List<List<E>> result = new ArrayList<List<E>>();
result.add(new ArrayList<E>());
return result;
}
E firstElement = original.remove(0);
List<List<E>> returnValue = new ArrayList<List<E>>();
List<List<E>> permutations = generatePerm(original);
for (List<E> smallerPermutated : permutations) {
for (int index=0; index <= smallerPermutated.size(); index++) {
List<E> temp = new ArrayList<E>(smallerPermutated);
temp.add(index, firstElement);
returnValue.add(temp);
}
}
return returnValue;
}
相关推荐
最新文章