如何使用arraylist以递归方式查找列表的排列?

时间:2014-10-15 14:12:24

标签: java recursion

嘿,我一直在四处寻找但无法找到解决这个问题的方法。我需要能够接收一个ArrayList并返回一个ArrayList,其中包含一组ArrayLists,用于原始的每个排列。

例如:

[2]返回[2]

[4,5]返回[[4,5],[5,4]]

[1,2,3]返回[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

这是我目前的代码,但显然存在一些问题:

public static List<List<Integer>> permutation(final List<Integer> list)
{
    // TO DO
    if (list.size() == 1)
    {
        List<List<Integer>> combinations = new ArrayList<List<Integer>>();
        combinations.add(list);
        return combinations;
    }

    int first = list.remove(0);

    List<List<Integer>> per = permutation(list);

    List<List<Integer>> permute = new ArrayList<List<Integer>>();

    for (List<Integer> li : per)
    {
        for (int index = 0; index <= li.size(); index++)
        {
            List<Integer> temp = new ArrayList<Integer>(li);
            temp.add(index, first);
            permute.add(temp);
        }
    }

    return permute;
}

1 个答案:

答案 0 :(得分:0)

private static List<List<Integer>> permutations(List<Integer> list) {
    return permutations(list, 0, list.size());
}

private static List<List<Integer>> permutations(List<Integer> list, int start, int end) {
    List<List<Integer>> permutations = new ArrayList<>();
    if (start < end) {
        Integer nextInt = list.get(start);
        if (start == end - 1) {
            permutations.add(Arrays.asList(nextInt));
        } else {
            for (List<Integer> subList : permutations(list, start + 1, end)) {
                for (int i = 0; i <= subList.size(); i++) {
                    List<Integer> newList = new ArrayList<>(subList);
                    newList.add(i, nextInt);
                    permutations.add(newList);
                }
            }
        }
    }
    return permutations;
}