-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path78.子集.cpp
More file actions
70 lines (68 loc) · 1.42 KB
/
78.子集.cpp
File metadata and controls
70 lines (68 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* @lc app=leetcode.cn id=78 lang=cpp
*
* [78] 子集
*
* https://leetcode-cn.com/problems/subsets/description/
*
* algorithms
* Medium (80.03%)
* Likes: 1307
* Dislikes: 0
* Total Accepted: 300.3K
* Total Submissions: 375K
* Testcase Example: '[1,2,3]'
*
* 给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
*
* 解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
*
*
*
* 示例 1:
*
*
* 输入:nums = [1,2,3]
* 输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
*
*
* 示例 2:
*
*
* 输入:nums = [0]
* 输出:[[],[0]]
*
*
*
*
* 提示:
*
*
* 1
* -10
* nums 中的所有元素 互不相同
*
*
*/
// @lc code=start
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
int num = 1<<nums.size();
vector<vector<int>> ans;
ans.reserve(num);
// 2**n种结果,从0-2**n-1,每种结果的二进制恰好表示nums的对应位置是否需要输出
for(int i=0;i<num;++i) {
vector<int> path;
for(int j=0;j<nums.size();++j) {
// 第i种结果的第j位是否需要输出
if(i>>j & 1) {
path.push_back(nums[j]);
}
}
ans.push_back(path);
}
return ans;
}
};
// @lc code=end