Given a set of distinct integers, S, return all possible subsets.
Note:
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;
}
};