47. 全排列 II

 

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        int length = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        
        if(length==0return res;
        Arrays.sort(nums);
        Deque<Integerpath = new ArrayDeque<>();
        boolean[] used = new boolean[length];
        dfs(nums, 0, length, used,res,path);
        return res;
    }
    public void dfs(int[] numsint depthint lengthboolean[] used,List<List<Integer>> res,Deque<Integerpath) {
        if (depth == length) {
            res.add(new ArrayList<>(path)); return;
        }
        for (int i = 0; i < length; i++) {
            if(used[i]) continue;
            if (i>0 && nums[i]==nums[i-1]&&!used[i-1]) continue;
            path.addLast(nums[i]);
            used[i] = true;
            dfs(nums, depth + 1, length, used,res,path);
            used[i] = false;
            path.removeLast();

        }
    }
}

 

posted @ 2022-02-25 10:41  zhangshuai2496689659  阅读(19)  评论(0)    收藏  举报