Skip to content

Latest commit

 

History

History
64 lines (44 loc) · 1.25 KB

20221014.md

File metadata and controls

64 lines (44 loc) · 1.25 KB

Algorithm

90. Subsets II

Description

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]

Example 2:

Input: nums = [0]
Output: [[],[0]]

Constraints:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10

Solution

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        subsetsWithDupHelper(nums, 0, res, new ArrayList<>());
        return res;
    }

    private void subsetsWithDupHelper(int[] nums, int pos, List<List<Integer>> res, List<Integer> tmpRes) {
        if(pos <= nums.length){
            res.add(new ArrayList<>(tmpRes));
        }
        for(int i=pos;i<nums.length;i++){
            if(i > pos && nums[i] == nums[i-1]) continue;   // avoid duplicates
            tmpRes.add(nums[i]);
            subsetsWithDupHelper(nums, i+1, res, tmpRes);
            tmpRes.remove(tmpRes.size()-1);
        }
    }
}

Discuss

Review

Tip

Share