首页 > 其他 > 详细

78. Subsets

时间:2016-03-17 19:45:50      阅读:130      评论:0      收藏:0      [点我收藏+]

Given a set of distinct integers, nums, 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 nums = [1,2,3], a solution is:

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


解法:

一个集合大小为n,则集合的子集个数为 2^n 

对集合进行编号,则(0,1,2,3,....2^n-1)

考察有2个元素的集合{1,2},则有4个子集,{[],[1],[2],[1,2]}

其编号可用00,01,10,11表示,

则可以看出,子集编号二进制位中,相应为是1的就在该子集中,

vector<vector<int>> subsets(vector<int>& nums) {
        int size=nums.size();
        vector<vector<int>> res;
        if(size==0)
            return res;
        
        long total=1<<size;
        sort(nums.begin(),nums.end());
        
        res.resize(total);
        
        for(int i=0;i<size;++i){
            long mask=1<<i;
            for(long j=0;j<total;++j){
                if(mask&j)
                    res[j].push_back(nums[i]);
            }
        }
        return res;
    }


78. Subsets

原文:http://searchcoding.blog.51cto.com/1335412/1752225

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