leetcode90 子集 II

code

class Solution {
    
    

    List<List<Integer>> res = new ArrayList<>();
    boolean[] vis;
    public List<List<Integer>> subsetsWithDup(int[] nums) {
    
    
        Arrays.sort(nums);
        vis = new boolean[nums.length];
        List<Integer> path = new ArrayList<>();
        backtrack(0, nums, path);
        return res;
    }

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

        if (id > 0 && nums[id - 1] == nums[id] && !vis[id - 1]){
    
    
            backtrack(id + 1, nums, path);
            return;
        }

        path.add(nums[id]);
        vis[id] = true;
        backtrack(id + 1, nums, path);
        path.remove(path.size() - 1);
        vis[id] = false;
        backtrack(id + 1, nums, path);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_50070650/article/details/112241899