码迷,mamicode.com
首页 > 其他好文 > 详细

#Leetcode# 90. Subsets II

时间:2018-11-25 01:20:04      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:bsp   代码   排序   subsets   hat   insert   targe   amp   cat   

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

标签:bsp   代码   排序   subsets   hat   insert   targe   amp   cat   

原文地址:https://www.cnblogs.com/zlrrrr/p/10014174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!