首页 > 其他 > 详细

【LeetCode】Subsets II

时间:2014-12-04 19:32:02      阅读:191      评论:0      收藏:0      [点我收藏+]

Subsets II

Given a collection of integers that might contain duplicates, S, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

 

For example,
If S = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

 

举例说明我的算法:

设S={1,2,2},则size=3

在不考虑重复的情况下,子集共有2^3=8个

分别为:

【1,2,2】

   0,0,0  {}

   0,0,1  {2}

   0,1,0  {2}

   0,1,1  {2,2}

   1,0,0  {1}

   1,0,1  {1,2}

   1,1,0  {1,2}

   1,1,1  {1,2,2}

1表示对应位的元素存在于集合中,0表示不存在。

因此只要从0遍历到2^size - 1,如果对应位为1,则将S中相应元素加入当前集合。

 

对于Note的两点要求:

1、sort函数对集合排序

2、使用map去重,存在即去除。

class Solution {
public:
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        vector<vector<int> > result;
        map<vector<int>, bool> m;
        int size = S.size();
        for(int i = 0; i < pow(2.0, size); i ++)
        {
            int tag = i;
            vector<int> cur;
            for(int j = size-1; j >= 0; j --)
            {
                if(!tag)
                    break;
                if(tag%2 == 1)
                {
                    cur.push_back(S[j]);
                }
                tag >>= 1;
            }
            sort(cur.begin(), cur.end());
            if(m.find(cur) == m.end()) 
            {
                m[cur] = true;
                result.push_back(cur);
            }
        }
        return result;
    }
};

bubuko.com,布布扣

【LeetCode】Subsets II

原文:http://www.cnblogs.com/ganganloveu/p/4143592.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!