|
| 1 | +// https://leetcode.com/problems/permutations |
| 2 | +// T: O(n * n!) |
| 3 | +// S: O(n * n!) |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.HashMap; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Map; |
| 9 | + |
| 10 | +public class Permutations { |
| 11 | + private static final Map<Integer, List<List<Integer>>> PERMUTATION_MASKS = new HashMap<>(); |
| 12 | + |
| 13 | + static { |
| 14 | + PERMUTATION_MASKS.put(1, List.of(List.of(0))); |
| 15 | + PERMUTATION_MASKS.put(2, List.of( |
| 16 | + List.of(0, 1), |
| 17 | + List.of(1, 0) |
| 18 | + )); |
| 19 | + PERMUTATION_MASKS.put(3, List.of( |
| 20 | + List.of(0, 1, 2), |
| 21 | + List.of(0, 2, 1), |
| 22 | + List.of(1, 0, 2), |
| 23 | + List.of(1, 2, 0), |
| 24 | + List.of(2, 0, 1), |
| 25 | + List.of(2, 1, 0) |
| 26 | + )); |
| 27 | + |
| 28 | + for (int i = 4 ; i <= 6 ; i++) { |
| 29 | + PERMUTATION_MASKS.put(i, getPermutationMask(i)); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + private static List<List<Integer>> getPermutationMask(int size) { |
| 34 | + final List<List<Integer>> result = new ArrayList<>(); |
| 35 | + final List<List<Integer>> previousPermutations = PERMUTATION_MASKS.get(size - 1); |
| 36 | + for (List<Integer> mask : previousPermutations) { |
| 37 | + for (int insertionPosition = 0 ; insertionPosition < size ; insertionPosition++) { |
| 38 | + result.add(newPermutation(mask, insertionPosition)); |
| 39 | + } |
| 40 | + } |
| 41 | + return result; |
| 42 | + } |
| 43 | + |
| 44 | + private static List<Integer> newPermutation(List<Integer> mask, int index) { |
| 45 | + final List<Integer> result = new ArrayList<>(); |
| 46 | + for (int i = 0 ; i < index ; i++) result.add(mask.get(i)); |
| 47 | + result.add(mask.size()); |
| 48 | + for (int i = index ; i < mask.size() ; i++) result.add(mask.get(i)); |
| 49 | + return result; |
| 50 | + } |
| 51 | + |
| 52 | + public List<List<Integer>> permute(int[] nums) { |
| 53 | + final List<List<Integer>> results = new ArrayList<>(); |
| 54 | + final List<List<Integer>> permutationMasks = PERMUTATION_MASKS.get(nums.length); |
| 55 | + for (List<Integer> mask : permutationMasks) { |
| 56 | + results.add(permute(nums, mask)); |
| 57 | + } |
| 58 | + return results; |
| 59 | + } |
| 60 | + |
| 61 | + private List<Integer> permute(int[] array, List<Integer> mask) { |
| 62 | + final int[] result = new int[array.length]; |
| 63 | + for (int i = 0 ; i < array.length ; i++) { |
| 64 | + result[mask.get(i)] = array[i]; |
| 65 | + } |
| 66 | + return toList(result); |
| 67 | + } |
| 68 | + |
| 69 | + private List<Integer> toList(int[] array) { |
| 70 | + final List<Integer> result = new ArrayList<>(array.length); |
| 71 | + for (int element : array) { |
| 72 | + result.add(element); |
| 73 | + } |
| 74 | + return result; |
| 75 | + } |
| 76 | +} |
0 commit comments