全排列的简单实现 java 回溯

介绍

从1到n的全排列,我们可以开一个vis数组表示这个数字是否在当前的排列方式种,回溯算法的全排列实际可以看作深度优先搜索

code

public class Test {
    
    

    static boolean[] vis = new boolean[100];

    public static void getPermutation
    (int n, int steps, List<Integer> path, List<List<Integer>> res){
    
    
        if (steps == n){
    
    
            res.add(new ArrayList<>(path));
        }
        for (int i = 1; i <= n; i++) {
    
    
            if (!vis[i]){
    
    
                vis[i] = true;
                path.add(i);
                getPermutation(n, steps + 1, path, res);
                path.remove(steps);
                vis[i] = false;
            }
        }
    }

    public static void main(String[] args) {
    
    
        Arrays.fill(vis, false);
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        getPermutation(8, 0, path, res);

        int cnt = 0;
        for (List<Integer> list: res){
    
    
            for(int x: list){
    
    
                System.out.print(x + " ");
            }
            ++cnt;
            System.out.println();
        }
        System.out.println("一共有" + cnt + "种排列方式");
    }
}

cnt等于n的阶乘,由于每次确定下一个要添加的元素都要遍历一遍1到n,所以总时间复杂度还为O(n*n!),还是很高的。

猜你喜欢

转载自blog.csdn.net/weixin_50070650/article/details/112208979
今日推荐