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; }
原文:http://searchcoding.blog.51cto.com/1335412/1752225