My Java backtrack method, easy to understand


  • 0
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        backtrack(res, new ArrayList<>(), nums, 0);
        return res;
    }
    
    private void backtrack(List<List<Integer>> res, List<Integer> cur, int[] nums, int start){
        if(start > nums.length){
            return;
        }
        
        res.add(new ArrayList<>(cur));
        
        for(int i = start; i < nums.length; i ++){
            if(i != start && nums[i] == nums[i - 1]){
                continue;
            }
            cur.add(nums[i]);
            backtrack(res, cur, nums, i + 1);
            cur.remove(cur.size() - 1);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.