Home Subsets II
Post
Cancel

LeetCode #90: Subsets II (C/C++).

medium

source: https://leetcode.com/problems/subsets-ii/
C/C++ Solution to LeetCode problem 90. Subsets II.

Problem


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.

Examples


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


This is very similar to problem 78, we will solve it using backtracking.

  • To prevent duplicates, we first sort the array of numbers, and when adding them to the current subset, we will skip the repeated numbers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
private:
  vector<vector<int>> powerset;
  void generateSets(vector<int>& nums, vector<int>& sol, int index) {
    powerset.push_back(sol);

    for (int i=index; i<nums.size(); i++) {
      if (i > index && nums[i] == nums[i-1])
        continue;
      sol.push_back(nums[i]);
      generateSets(nums, sol, i+1);
      sol.pop_back();
    }
  }

public:
  vector<vector<int>> subsetsWithDup(vector<int>& nums) {
    vector<int> sol;
    sort(nums.begin(), nums.end());
    generateSets(nums, sol, 0);
    return powerset;
  }
};
This post is licensed under CC BY 4.0 by the author.

Partition List

Decode Ways