LeetCode 78:Subsets

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 




  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值