-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathPermutations.java
76 lines (67 loc) · 2.48 KB
/
Permutations.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
70
71
72
73
74
75
76
// https://leetcode.com/problems/permutations
// T: O(n * n!)
// S: O(n * n!)
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Permutations {
private static final Map<Integer, List<List<Integer>>> PERMUTATION_MASKS = new HashMap<>();
static {
PERMUTATION_MASKS.put(1, List.of(List.of(0)));
PERMUTATION_MASKS.put(2, List.of(
List.of(0, 1),
List.of(1, 0)
));
PERMUTATION_MASKS.put(3, List.of(
List.of(0, 1, 2),
List.of(0, 2, 1),
List.of(1, 0, 2),
List.of(1, 2, 0),
List.of(2, 0, 1),
List.of(2, 1, 0)
));
for (int i = 4 ; i <= 6 ; i++) {
PERMUTATION_MASKS.put(i, getPermutationMask(i));
}
}
private static List<List<Integer>> getPermutationMask(int size) {
final List<List<Integer>> result = new ArrayList<>();
final List<List<Integer>> previousPermutations = PERMUTATION_MASKS.get(size - 1);
for (List<Integer> mask : previousPermutations) {
for (int insertionPosition = 0 ; insertionPosition < size ; insertionPosition++) {
result.add(newPermutation(mask, insertionPosition));
}
}
return result;
}
private static List<Integer> newPermutation(List<Integer> mask, int index) {
final List<Integer> result = new ArrayList<>();
for (int i = 0 ; i < index ; i++) result.add(mask.get(i));
result.add(mask.size());
for (int i = index ; i < mask.size() ; i++) result.add(mask.get(i));
return result;
}
public List<List<Integer>> permute(int[] nums) {
final List<List<Integer>> results = new ArrayList<>();
final List<List<Integer>> permutationMasks = PERMUTATION_MASKS.get(nums.length);
for (List<Integer> mask : permutationMasks) {
results.add(permute(nums, mask));
}
return results;
}
private List<Integer> permute(int[] array, List<Integer> mask) {
final int[] result = new int[array.length];
for (int i = 0 ; i < array.length ; i++) {
result[mask.get(i)] = array[i];
}
return toList(result);
}
private List<Integer> toList(int[] array) {
final List<Integer> result = new ArrayList<>(array.length);
for (int element : array) {
result.add(element);
}
return result;
}
}