90. Subsets II

  • Difficulty: Medium

  • Topics: Array, Backtracking

  • Similar Questions:

Problem:

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

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

Solutions:

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        sort(nums.begin(), nums.end());

        vector<int> path;
        vector<vector<int>> ret;

        helper(nums, 0, path, ret);

        return ret;
    }

    void helper(vector<int>& nums, int pos, vector<int>& path, vector<vector<int>>& ret) {
        if (pos == nums.size()) {
            ret.push_back(path);
            return;
        }

        path.push_back(nums[pos]);
        helper(nums, pos + 1, path, ret);
        path.pop_back();

        while (pos + 1 < nums.size() && nums[pos + 1] == nums[pos]) ++pos;
        helper(nums, pos + 1, path, ret);
    }
};

results matching ""

    No results matching ""