|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | import java.util.ArrayList;
|
| 4 | +import java.util.HashSet; |
4 | 5 | import java.util.List;
|
| 6 | +import java.util.Set; |
5 | 7 |
|
6 | 8 | public class _46 {
|
7 | 9 |
|
@@ -29,4 +31,41 @@ private List<List<Integer>> backtracking(int[] nums, int index, List<List<Intege
|
29 | 31 | }
|
30 | 32 | }
|
31 | 33 |
|
| 34 | + public static class Solution2 { |
| 35 | + /** |
| 36 | + * My completely original solution on 10/11/2021, although a little verbose and super as efficient as the above one. |
| 37 | + * Basically, insert the next unused number into all possible positions in the currently formed list, |
| 38 | + * as soon as the size of this list equals nums.length, add this new permutation into the result; |
| 39 | + * I'll have to use a HashSet to filter out duplicates. |
| 40 | + */ |
| 41 | + public List<List<Integer>> permute(int[] nums) { |
| 42 | + Set<List<Integer>> ans = new HashSet<>(); |
| 43 | + boolean[] used = new boolean[nums.length]; |
| 44 | + backtracking(new ArrayList<>(), nums, ans, used); |
| 45 | + List<List<Integer>> result = new ArrayList<>(); |
| 46 | + for (List<Integer> list : ans) { |
| 47 | + result.add(list); |
| 48 | + } |
| 49 | + return result; |
| 50 | + } |
| 51 | + |
| 52 | + private void backtracking(List<Integer> list, int[] nums, Set<List<Integer>> ans, boolean[] used) { |
| 53 | + if (list.size() == nums.length) { |
| 54 | + ans.add(new ArrayList<>(list)); |
| 55 | + return; |
| 56 | + } |
| 57 | + for (int i = 0; i <= list.size(); i++) { |
| 58 | + for (int j = 0; j < nums.length; j++) { |
| 59 | + if (!used[j]) { |
| 60 | + used[j] = true; |
| 61 | + list.add(i, nums[j]); |
| 62 | + backtracking(list, nums, ans, used); |
| 63 | + used[j] = false; |
| 64 | + list.remove(i); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
32 | 71 | }
|
0 commit comments