#Leetcode# 90. Subsets II

Posted 丧心病狂工科女

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#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;
        }
    }
};

 

以上是关于#Leetcode# 90. Subsets II的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 90. Subsets II 子集合 II

Leetcode 90. Subsets II

[leetcode-90-Subsets II]

Leetcode 90: Subsets II

Leetcode 90. Subsets II

LeetCode 90. Subsets II