Given a set of distinct integers, S, 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 S = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
解题思路:
由于题目已经说明S集合中数字都不同,所以子集一定有2^n个,初步估计一下后台数据中的n值
应该不会大于32的,所以我们可用一个整数的二进制表示某个数字时候是否出现在集合中,然后枚举
即可.
解题代码:
class Solution {
public:
vector
> subsets(vector
&S) { int n = S.size(); sort(S.begin(),S.end()); vector
> res; for (int i = 0; i < 1 << n; ++i) { vector
vec ; int tmp = i , cnt = 0 ; while (tmp) { if (tmp & 1) vec.push_back(S[cnt]); tmp >>= 1 , ++cnt ; } res.push_back(vector
(vec.begin(),vec.end())); } return res; } };