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

AHa*_*ert 2 java permutation

我正在尝试获取与输入 arrayList 长度相同的 ArrayList 的所有可能排列。即 1,2,3 的 ArrayList 将导致 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);
            }
        }

    }
Run Code Online (Sandbox Code Playgroud)

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

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

Ben*_*ema 5

看看 Guava 的Collections2 permutations方法。

示例(来源

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]
*/
Run Code Online (Sandbox Code Playgroud)