90. Subsets II

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],
  []
]

AC code:

class Solution {
private:
    void helper(int begin, int len, vector<int> temp, vector<vector<int>>& res, vector<int> nums) {
        res.push_back(temp);
        for (int i = begin; i < len; ++i) {
            if (i != begin && nums[i] == nums[i-1]) continue;
            temp.push_back(nums[i]);
            helper(i+1, len, temp, res, nums);
            temp.pop_back();
        }
    }
    
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        vector<int> temp;
        vector<vector<int>> res;
        sort(nums.begin(), nums.end());
        int len = nums.size();
        helper(0, len, temp, res, nums);
        return res;
    }
};
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Subsets II.

 

 

posted @ 2018-10-28 16:49  Veritas_des_Liberty  阅读(296)  评论(0编辑  收藏  举报