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

标签 java algorithm

在 main 方法中打印时,变量“result”为空。 有人可以指导我如何构建代码吗? Java新手。如果问题很幼稚,我们深表歉意。

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;                     
        }                       
    }
}

最佳答案

您的问题是在每个递归调用中对 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;
        }
    }
}

调用主程序后,输出为:

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

关于java - 试图找到整数数组元素的所有排列的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48141905/

相关文章:

java - 从数组中随机选取一个索引,显示在 TextView 中

java - 做 while 与 try catch 附上的麻烦

algorithm - 用于合并唯一键的最快 KV 数据结构?

java.net.InetSocketAddress 和 java.net.SocketAddress 是否支持 IPv6?

java - Android Phonegap 2.1 > 2.2 升级错误

algorithm - 是否可以在 O(logn) 中测试一个数是否为素数?

algorithm - 快速排序的尾调用优化

algorithm - 关系数据库与图数据库的转换

c - 有符号整数的谓词 "less than or equal"的高效并行字节计算

java - 使用 Google App Engine 的网络服务