LeetCode 78:Subsets

来源:互联网 发布:Linux进入根目录的命令 编辑:程序博客网 时间:2024/06/08 04:43

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

Subscribe to see which companies asked this question

方法一:循环添加,在原子集的基础上,不断添加新的元素

class Solution {public:vector<vector<int>> subsets(vector<int>& nums) {vector<vector<int>> ans(1, vector<int>());sort(nums.begin(), nums.end());for (int i = 0; i < nums.size(); i++){int n = ans.size();for (int j = 0; j < n; j++) //第二个for循环是为了求得包含nums[i]的所有子集{ans.push_back(ans[j]); //在尾部重新插入ans已经存在的子集ans.back().push_back(nums[i]); //将nums[i]添加进去}}return ans;}};

例如:nums={1,2,3}时,求所有的子集






方法二:位操作

class Solution {public:vector<vector<int>> subsets(vector<int>& nums) {sort(nums.begin(), nums.end());int n = pow(2, nums.size());vector<vector<int>> ans(n, vector<int>());for (int i = 0; i < nums.size(); i++){for (int j = 0; j < n; j++) {if ((j >> i) & 1 == true)ans[j].push_back(nums[i]);}}return ans;}};


例如,nums={1,2,3},子集的可能结果:

  1   ->          取 or 不取 = 2 
  2   ->          取 or 不取 = 2  

  3   ->          取 or 不取 = 2 

nums的子集对nums中的每个元素来说,只有两种选择,就是“取”和“不取”,一共有2^3=8个子集{ { } , {1} , {2} , {3} , {1,2} , {1,3} , {2,3} , {1,2,3} },给每个元素分配位  -> 第一个位给元素1 ,第二个位给元素2,第三个位给元素3,取 = 1,不取 = 0


0) 0 0 0  -> 不取3, 不取2, 不取1 = {} 
1) 0 0 1  -> 不取3, 不取2, 取   1 = {1} 
2) 0 1 0  -> 不取3, 取   2, 不取1 = {2} 
3) 0 1 1  -> 不取3, 取   2, 取   1 = {1,2} 
4) 1 0 0  -> 取   3, 不取2, 不取1 = {3} 
5) 1 0 1  -> 取   3, 不取2, 取   1 = {1,3} 
6) 1 1 0  -> 取   3, 取   2, 不取1 = {2,3} 
7) 1 1 1  -> 取   3, 取   2, 取   1 = {1,2,3} 

根据上面可以发现,插入S[i]的条件是((j>>i)&1 ==true),其中j属于{ 0,1,2,3,4,5,6,7 }

1.元素1被插入的子集,只有当j的第一位是1时: if( j >> 0 &1 )  ==> ( j )= 1 , 3 , 5 , 7 
2.元素2被插入的子集,只有当j的第二位是1时: if( j >> 1 &1 )  ==>( j ) = 2 , 3 , 6 , 7
3.元素3被插入的子集,只有当j的第三位是1时: if( j >> 2 & 1 ) ==>( j ) = 4 , 5 , 6 , 7 




1 0