-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubsets.java
More file actions
56 lines (52 loc) · 1.24 KB
/
Subsets.java
File metadata and controls
56 lines (52 loc) · 1.24 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
package medium;
import java.util.ArrayList;
import java.util.List;
/**
*
* ClassName: Subsets
* @author chenyiAlone
* Create Time: 2019/04/07 22:58:10
* Description: No.78
* 思路:
* 1. 移位操作
* 1). maxi = 1 << len;
* 2). i = 0 -> maxi
* j = 0 -> size
* 3). ((1 << j) & i) != 0
*
* 2. DFS
*
*
* 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],
[]
]
*/
public class Subsets {
public List<List<Integer>> subsets(int[] nums) {
int len = nums.length;
int maxi = 1 << len;
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < maxi; i++) {
List<Integer> tmp = new ArrayList<>();
for (int j = 0; j < len; j++) {
if (((1 << j) & i) != 0) {
tmp.add(nums[j]);
}
}
res.add(new ArrayList<Integer>(tmp));
}
return res;
}
}