Algo-Sim › Recursion & Backtracking

Subsets II

Medium · Recursion & Backtracking · step through it in Java, Python and C++ on your own input

Every distinct subset when the input has duplicates: sort, then skip a value equal to the one just tried at the same depth.

Problem

Given an array nums that may contain repeated values, return every distinct subset. Subsets with the same values count once, whatever positions they came from.

Constraints

Edge cases to test

Follow-up questions

Why skip only at the same depth?
Choosing the second copy after the first is a new subset; choosing it instead of the first at the same position repeats one.
Is there a counting alternative?
Group equal values with their counts and choose 0..count copies of each: same output, no skip rule.

Solution

Java

List<List<Integer>> result = new ArrayList<>();

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

void backtrack(int[] nums, int start, List<Integer> path) {
    result.add(new ArrayList<>(path));
    for (int i = start; i < nums.length; i++) {
        if (i > start && nums[i] == nums[i - 1]) continue;
        path.add(nums[i]);
        backtrack(nums, i + 1, path);
        path.remove(path.size() - 1);
    }
}

Python

def subsets_with_dup(nums):
    nums = sorted(nums)
    result = []

    def backtrack(start, path):
        result.append(path[:])
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue
            path.append(nums[i])
            backtrack(i + 1, path)
            path.pop()

    backtrack(0, [])
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<vector<int>> result = {};

    vector<vector<int>> subsetsWithDup(vector<int> &nums) {
        sort(nums.begin(), nums.end());
        vector<int> path;
        backtrack(nums, 0, path);
        return result;
    }

    void backtrack(vector<int> &nums, int start, vector<int> &path) {
        result.push_back(path);
        for (int i = start; i < int(nums.size()); i++) {
            if (i > start && nums[i] == nums[i - 1])
                continue;
            path.push_back(nums[i]);
            backtrack(nums, i + 1, path);
            path.pop_back();
        }
    }
};

More Recursion & Backtracking problems