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个子集。即n个数字的组合情况,可用n个bits进行表示,bit位与数组是一一对应;
判断每个bit是否为1 进行枚举。
class Solution { public: vector<vector <int> > subsets(vector<int>& nums) { sort(nums.begin(),nums.end()); vector< vector<int> > ans; int n = nums.size(); int i = 0,j= 0; for(i = 0;i< 1 << n;i++) { vector<int> temp; int index = 0; int count = i; while(count != 0) { if(count & 1 == 1) { temp.push_back(nums[index]); } index++; count = count >> 1; } ans.push_back(temp); } return ans; } };