``````Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]``````

迭代法 常规解法

``````class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> subs = {{}};
for (int num : nums) {
int n = subs.size();
for (int i = 0; i < n; i++) {
subs.push_back(subs[i]);
subs.back().push_back(num);
}
}
return subs;
}
}; ``````

``````Runtime: 4 ms, faster than 97.25% of C++ online submissions for Subsets.
Memory Usage: 6.6 MB, less than 100.00% of C++ online submissions for Subsets.``````

递归方法 常规解法

``````class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> subs;
vector<int> sub;
subsets(nums, 0, sub, subs);
return subs;
}
private:
void subsets(const vector<int>& nums, int i, vector<int>& sub, vector<vector<int>>& subs) {
subs.push_back(sub);
for (int j = i; j < nums.size(); j++) {
sub.push_back(nums[j]);
subsets(nums, j + 1, sub, subs);
sub.pop_back();
}
}
};``````

位运算 可遇而不可求

000 对应 { }
001 对应 {3}
010 对应 {2}
011 对应 {2,3}
100 对应 {1}
101 对应 {1,3}
110 对应 {1,2}
111 对应 {1,2,3}

``````class Solution {
public:
vector<vector<int> > subsets(vector<int> &nums) {
int elem_num = nums.size();
//元素总个数
int subset_num = pow (2, elem_num);
vector<vector<int> > subset_set (subset_num, vector<int>());
for (int i = 0; i < elem_num; i++)
for (int j = 0; j < subset_num; j++)
if ((j >> i) & 1)
subset_set[j].push_back (nums[i]);
return subset_set;
}
};``````