gpt4 book ai didi

java - 获取 ArrayList 所有可能排列的 ArrayList

转载 作者:行者123 更新时间:2023-12-02 07:57:42 26 4
gpt4 key购买 nike

我试图获取与输入 arrayList 长度相同的 ArrayList 的所有可能排列。 IE。 ArrayList 为 1,2,3 将导致 123, 132, 213, 231, 321, 312,不包括较短的排列,如 1, 2, 12, 13... 等。这是我到目前为止的代码:

public void getAllPermutations(ArrayList<coordinate> coords) {
ArrayList<coordinate> sub = new ArrayList<coordinate>();
permutateSub(sub, coords);
}

private ArrayList<ArrayList<coordinate>> permutateSub(ArrayList<coordinate> sub,
ArrayList<coordinate> coords) {
int n = coords.size();
if(n == 0) System.out.println(sub);
else {
if(sub.size()==n) {
System.out.println(sub);
for(int i = 0; i<n; i++) {
ArrayList<coordinate> a = new ArrayList<coordinate>(sub);
a.add(coords.get(i));
ArrayList<coordinate> b = new ArrayList<coordinate>(coords);
b.remove(i);
permutateSub(a, b);
}
}

}

坐标是一个只有 x、y 的类,并被访问以保存项目的 2D 点。

目前,我正在使用此代码将其打印到控制台,但如果有人能够阐明我如何将其存储到 ArrayList>,我也将不胜感激。谢谢。

最佳答案

看看 Guava 的 Collections2 permutations方法。

示例 ( source )

public void permutations () {
List<Integer> vals = Ints.asList(new int[] {1, 2, 3});

Collection<List<Integer>> orderPerm = Collections2.permutations(vals);

for (List<Integer> val : orderPerm) {
logger.info(val);
}
}

/* output:
[1, 2, 3]
[1, 3, 2]
[3, 1, 2]
[3, 2, 1]
[2, 3, 1]
[2, 1, 3]
*/

关于java - 获取 ArrayList 所有可能排列的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25704754/

26 4 0