↻one more pass.
Backtracking · Medium

Subsets II: the idea to remember.

Return all distinct subsets when the input array may contain duplicate integers.

Solve on LeetCode ↗

The core insight

Sort values and skip equal candidates only when they compete at the same recursion depth.

Why it works

Equal choices at one depth generate identical subsets, while equal values at deeper depths represent valid multiplicities.

The mistake to avoid

Do not skip every repeated value: a subset may legitimately contain two copies.

Time: O(n · 2^n) including outputSpace: O(n) auxiliary plus output

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Sort values and skip equal candidates only when they compete at the same recursion depth.
public List<List<Integer>> subsetsWithDup(int[] nums) {
    Arrays.sort(nums);
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    subSet(nums, 0, ans, list);
    return ans;
}

public void subSet(
    int[] nums,
    int idx,
    List<List<Integer>> ans,
    List<Integer> list
) {
    ans.add(new ArrayList<>(list));

    for (int i = idx; i < nums.length; i++) {

        if (i > idx && nums[i] == nums[i - 1]) continue;
        list.add(nums[i]);
        subSet(nums, i + 1, ans, list);
        list.remove(list.size() - 1);
    }
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.