# 子集

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

 

示例 1:

输入:nums = [1,2,3]
输出:
[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

示例 2:

输入:nums = [0]
输出:
[[],[0]]

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; vector nums = {1, 2, 3}; vector> res; res = sol.subsets(nums); for (auto i : res) { for (auto j : i) cout << j << " "; cout << endl; } return 0; } ``` ## 答案 ```cpp class Solution { private: void subsetss(int numssize, int i, vector &nums, vector> &output, vector &newtemp) { if (i >= numssize) { output.push_back(newtemp); return; } newtemp.push_back(nums[i]); subsetss(numssize, i + 1, nums, output, newtemp); newtemp.pop_back(); } public: vector> subsets(vector &nums) { int numssize = nums.size(); int i = 0; vector> output; vector newtemp; subsetss(numssize, i, nums, output, newtemp); return output; } }; ``` ## 选项 ### A ```cpp class Solution { public: vector> subsets(vector &nums) { int numssize = nums.size(); int numscount = 1 << numssize; vector> output; int i = 0; while (i < numscount) { vector newtemp; for (int x = 0; x < numssize; x++) { if ((1 << x) & i) { newtemp.push_back(nums[x]); } } i++; output.push_back(newtemp); } return output; } }; ``` ### B ```cpp class Solution { public: vector> subsets(vector &nums) { vector> output; vector subset; int length = nums.size(); output.push_back(subset); int current = 0; int output_size; while (current < length) { output_size = output.size(); for (int i = 0; i < output_size; i++) { vector newinsert = output[i]; newinsert.insert(newinsert.end(), nums[current]); output.push_back(newinsert); } current++; } return output; } }; ``` ### C ```cpp class Solution { public: vector> subsets(vector &nums) { vector> res; if (nums.empty()) return res; res.push_back({}); int n = nums.size(); for (int i = 0; i < n; i++) { int nRes = res.size(); for (int j = 0; j < nRes; j++) { vector temp = res[j]; temp.push_back(nums[i]); res.push_back(temp); } } return res; } }; ```