#Leetcode# 90. Subsets II

https://leetcode.com/problems/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],
  []
]

题解:$nums$ 要排序

代码:

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        int n = nums.size();
        set<vector<int>> ans;
        vector<int> v;
        vector<int> cnt;
        sort(nums.begin(), nums.end());
        for(int i = 0; i < (1 << n); i ++) {
            v.clear();
            cnt.clear();
            A(v, i);
            for(int j = 0; j < v.size(); j ++) 
                if(v[j] == 1)     
                cnt.push_back(nums[j]);  
            ans.insert(cnt);
        }
       
        return vector<vector<int>>(ans.begin(), ans.end());
    }
    void A(vector<int> &v, int x) {
        while(x) {
            v.push_back(x % 2);
            x /= 2;
        }
    }
};

 

posted @ 2018-11-24 23:42  丧心病狂工科女  阅读(97)  评论(0编辑  收藏  举报