我正在尝试,给定一些整数 ArrayList,创建该列表的所有排列。我想将每个排列(一个 ArrayList 本身)存储在一个更大的 ArrayList 的 ArrayList 中。我可以找到排列并毫无问题地将每个排列打印到控制台。我还没有找到成功将它们添加到列表中的方法。我目前的尝试如下所示。
//myList is a field that I need to use elsewhere
//a is the ArrayList of Integers
//initially, n is a.size()
private static void perm2(ArrayList<ArrayList<Integer>> myList,
ArrayList<Integer> a, int n)
{
for (int i = 0; i < n; i++)
{
swap(a, i, n-1);
perm2(where, a, n-1);
swap(a, i, n-1);
}
if (n == 1)
{
System.out.println(a.toString());
myList.add(a);
return;
}
}
这是给定 [0, 1, 2] 的输出:
[1, 2, 0]
[2, 1, 0]
[2, 0, 1]
[0, 2, 1]
[1, 0, 2]
[0, 1, 2]
[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
打印代码将正确的内容发送到控制台,那么为什么不在之后立即添加正确的内容呢?如果这不是解决问题的好方法,我应该朝哪个方向看?最终,这些索引可以按每个顺序从列表中检索数据。
提前致谢。
我应该注意,在合理的计算能力范围内,输入列表可以是任意长度。
编辑:我的疏忽。这是交换代码:
private static void swap(ArrayList<Integer> list, int a, int b)
{
T temp = list.get(a);
list.set(a, list.get(b));
list.set(b, temp);
}
最佳答案
您总是在列表的列表中存储相同的列表。然后你交换它的元素并再次存储它。所以你最终得到了对同一个列表的 N 个引用。在将列表存储到列表的列表之前,您需要制作列表的副本:
myArray.add(new ArrayList<>(a));
关于java - 进行排列后,如何将它们添加到数组中? [ java ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25047454/