试图找到整数数组元素的所有排列的集合

时间:2018-01-07 21:55:28

标签: java algorithm

变量'结果'在main方法中打印时为空白。 有人可以指导我如何构建代码吗? Java新手。如果Q天真就道歉。

import java.util.ArrayList;
import java.util.List;

public class StringPermutation {

    public static void main(String[] args){
        int[] a = new int[]{1,2,3};
        System.out.println(permute(a)); 
    }

    public static List<List<Integer>> permute(int[] a) {        
        List<Integer> path = new ArrayList<>();
        List<List<Integer>> result = new ArrayList(path);
        boolean[] visited = new boolean[a.length];
        helper(result, path, visited, a);
        //System.out.println(result);
        return result;
    }

    private static void helper(List<List<Integer>> result, List<Integer> path, boolean[] visited, int[] a) {
        if (path.size() == a.length)
            result.add(path);           

        for (int i = 0; i < a.length; i++) {
            if (visited[i]) continue;
            path.add(a[i]);
            visited[i] = true;
            helper(result, path, visited, a );
            path.remove(path.size() - 1);
            visited[i] = false;                     
        }                       
    }
}

1 个答案:

答案 0 :(得分:1)

您的问题是每次递归调用中对spells列表的引用。

当递归条件为path时,您必须克隆true列表或添加通过当前path列表的新列表:

path
//This constructor will create a new List adding the elements of `path`.
result.add(new ArrayList<>(path)); 

调用主程序后,输出将为:

public class StringPermutation {

    public static void main(String[] args) {
        int[] a = new int[]{1, 2, 3};
        System.out.println(permute(a));
    }

    public static List<List<Integer>> permute(int[] a) {
        List<Integer> path = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        boolean[] visited = new boolean[a.length];
        helper(result, path, visited, a);
        //System.out.println(result);
        return result;
    }

    private static void helper(List<List<Integer>> result, List<Integer> path, boolean[] visited, int[] a) {
        if (path.size() == a.length)
            result.add(new ArrayList<>(path));

        for (int i = 0; i < a.length; i++) {
            if (visited[i]) continue;
            path.add(a[i]);
            visited[i] = true;
            helper(result, path, visited, a);
            path.remove(path.size() - 1);
            visited[i] = false;
        }
    }
}