回溯-全排列

1)数字不能重复使用(同一树枝不能重复)

使用used辅助数组,使用就改为true

2)排列不可重复(同一树层不可重复)

if (i >0 &&nums[i] == nums[i-1] && used[i-1] == false){
                //used[i-1] == false  说明同一数层使用过
                //used[i] == true  说明同一树枝使用过
                continue;
            }

i>0是防止数组索引i-1越界

3)整体代码

public static void main(String[] args) {
        int nums[] = {1,1,2};
        System.out.println(new T01().permuteUnique(nums));
    }
    //给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new LinkedList<>();
        boolean[] used = new boolean[nums.length];
        dfs(nums, res, path, used);
        return res;
    }

    private void dfs(int[] nums, List<List<Integer>> res, List<Integer> path, boolean[] used) {
        if (path.size() == nums.length){
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (i >0 &&nums[i] == nums[i-1] && used[i-1] == false){
                //used[i-1] == false  说明同一数层使用过
                //used[i] == true  说明同一树枝使用过
                continue;
            }
            if (used[i] == false){
                path.add(nums[i]);
                used[i] = true;//标记为使用过
                dfs(nums, res, path, used);
                path.remove(path.size()-1);
                used[i] = false;
            }

        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值