Subsets II

Medium BacktrackingArray

Problem

Given an integer array which may contain duplicates, return every distinct subset (the power set, deduped). The result may be 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

Approach — Backtracking

This is a Backtracking problem. The idea: build candidates one choice at a time and abandon a branch the moment it can't lead to a valid answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: exponential worst case.

Solution code

Python

class Solution:
    def subsetsWithDup(self, nums):
        nums.sort()
        res = []
        def bt(start, cur):
            res.append(cur[:])
            for i in range(start, len(nums)):
                if i > start and nums[i] == nums[i-1]:
                    continue
                cur.append(nums[i])
                bt(i + 1, cur)
                cur.pop()
        bt(0, [])
        return res

Java

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

    private void backtrack(List<List<Integer>> result, List<Integer> current,
                           int[] nums, int start) {
        result.add(new ArrayList<>(current));
        for (int i = start; i < nums.length; i++) {
            // Skip duplicates at the same recursion depth — same-value
            // siblings would produce the same subset twice otherwise.
            if (i > start && nums[i] == nums[i - 1]) {
                continue;
            }
            current.add(nums[i]);
            backtrack(result, current, nums, i + 1);
            current.remove(current.size() - 1);
        }
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Subsets II interactively → ← All solutions