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

Subsets II

时间:2019-05-26 00:09:52      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:The   duplicate   return   push   i++   note   not   empty   art   

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

code1:

class Solution
{
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums)
    {
        if(nums.empty())
            return {{}};

        vector<vector<int>> res;
        vector<int> tmp;
        set<vector<int>> s;
        subsetsWithDup(0,tmp,s,res,nums);
        return res;
    }
private:
    void subsetsWithDup(int start,vector<int> &tmp,set<vector<int>> &s,vector<vector<int>> &res,vector<int>& nums)
    {
        if(start==nums.size())
        {

            vector<int> t(tmp);
            sort(t.begin(),t.end());
            if(s.find(t)==s.end())
            {
                s.insert(t);
                res.push_back(t);
            }
            return;
        }

        tmp.push_back(nums.at(start));
        subsetsWithDup(start+1,tmp,s,res,nums);
        tmp.pop_back();
        subsetsWithDup(start+1,tmp,s,res,nums);

        return ;
    }
};

code2

class Solution
{
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums)
    {
        if(nums.empty())
            return {{}};

        sort(nums.begin(),nums.end());
        vector<vector<int>> res;
        vector<int> tmp;
        subsetsWithDup(0,tmp,nums,res);
        return res;
    }
private:
    void subsetsWithDup(int start,vector<int> &tmp,vector<int>& nums,vector<vector<int>> &res)
    {
        res.push_back(tmp);
        for(int i=start;i<nums.size();)
        {
            int first=i++;
            while(i<nums.size()&&nums.at(first)==nums.at(i))
                ++i;
            tmp.push_back(nums.at(first));
            subsetsWithDup(first+1,tmp,nums,res);
            tmp.pop_back();
        }
        return;
    }
};

 

Subsets II

标签:The   duplicate   return   push   i++   note   not   empty   art   

原文地址:https://www.cnblogs.com/tianzeng/p/10924531.html

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