Java 实现全排列算法

算法时间复杂度为 n!
使用回溯算法实现

    //全排列
    static LinkedList<LinkedList<Integer>> res = new LinkedList<>();
    public void solution1(int[] nums, LinkedList<Integer> hasSel){
        if (hasSel.size() == nums.length){//全排列结束,选3个数字
            res.add(new LinkedList<>(hasSel));
            return ;
        }
        for (int i = 0; i < nums.length; i++) {
            if (hasSel.contains(nums[i])) continue;//排除已经选过的
            hasSel.add(nums[i]);//做选择
            solution1(nums, hasSel);//进入下一个决策树
            hasSel.removeLast();//回溯,取消选择
        }
    }

使用交换算法实现

    public void solution2(int[] nums, int start, int end){
        if (start == end){
            for (int i:nums
                 ) {
                System.out.print(i + " ");
            }
            System.out.println();
            return ;
        }
        for (int i = start; i <= end; i++) {
            swap(nums, i,start);
            solution2(nums, start + 1, end);
            swap(nums, i, start);
        }
    }

    public void swap(int[] nums, int i, int start) {
        int temp = nums[i];
        nums[i] = nums[start];
        nums[start] = temp;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值