forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_78.java
69 lines (58 loc) · 1.83 KB
/
_78.java
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
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
/**
* 78. Subsets
* Given a set of distinct integers, nums, return all possible subsets.
* Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
*/
public class _78 {
public static class IterativeSolution {
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList();
List<Integer> empty = new ArrayList();
result.add(empty);
if (nums == null) {
return result;
}
for (int i = 0; i < nums.length; i++) {
List<List<Integer>> temp = new ArrayList();
//you'll have to create a new one here, otherwise, it'll throw ConcurrentModificationException.
for (List<Integer> list : result) {
List<Integer> newList = new ArrayList(list);
newList.add(nums[i]);
temp.add(newList);
}
result.addAll(temp);
}
return result;
}
}
public static class BacktrackingSolution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList();
backtracking(result, new ArrayList(), nums, 0);
return result;
}
void backtracking(List<List<Integer>> result, List<Integer> temp, int[] nums, int start) {
result.add(new ArrayList(temp));
for (int i = start; i < nums.length; i++) {
temp.add(nums[i]);
backtracking(result, temp, nums, i + 1);
temp.remove(temp.size() - 1);
}
}
}
}