获取ArrayList的所有可能排列的ArrayList [英] Get ArrayList of all possible permutations of an ArrayList

查看:202
本文介绍了获取ArrayList的所有可能排列的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获得与输入arrayList长度相同的ArrayList的所有可能排列。即一个1,2,3的ArrayList会产生123,132,213,231,321,312,不包括像1,2,12,13等更短的排列。这是我到目前为止的代码:

I am trying to get all possible permutations of an ArrayList that are the same length as the input arrayList. I.e. an ArrayList of 1,2,3 would result in 123, 132, 213, 231, 321, 312, not including the shorter permutations like 1, 2, 12, 13... etc. Here is the code I have so far:

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点。

A coordinate is a class that just has x, y, and visited to hold 2D points for a project.

目前我正在使用此代码将其打印到控制台,但我如果有人可以了解我将如何将其存储到ArrayList中,也会感激不尽。谢谢。

Currently I am using this code to print it to the console, but I would also appreciate it if someone could shed some light into how I would store this into an ArrayList>. Thanks.

推荐答案

这是一种方法:

public static void permutation(List<coordinate> nums) {
    List<List<coordinate>> accum = new ArrayList<List<coordinate>>();
    permutation(accum, Arrays.<coordinate>asList(), nums);
    System.out.println(accum);
}

private static void permutation(List<List<coordinate>> accum, List<coordinate> prefix, List<coordinate> nums) {
    int n = nums.size();
    if (n == 0) {
        accum.add(prefix);
    } else {
        for (int i = 0; i < n; ++i) {
            List<coordinate> newPrefix = new ArrayList<coordinate>();
            newPrefix.addAll(prefix);
            newPrefix.add(nums.get(i));
            List<coordinate> numsLeft = new ArrayList<coordinate>();
            numsLeft.addAll(nums);
            numsLeft.remove(i);
            permutation(accum, newPrefix, numsLeft);
        }
    }
}

这篇关于获取ArrayList的所有可能排列的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆