|
5 | 5 |
|
6 | 6 | public class Permutations46 {
|
7 | 7 |
|
8 |
| - public static List<List<Integer>> permute(int[] nums) { |
| 8 | + public static List<List<Integer>> permute1(int[] nums) { |
9 | 9 | List<List<Integer>> list = new ArrayList<>();
|
10 | 10 | ArrayList<Integer> templist = new ArrayList<>();
|
11 |
| - |
12 |
| - permute(nums, templist, list); |
13 |
| - |
| 11 | + |
| 12 | + permute1(nums, templist, list); |
| 13 | + |
14 | 14 | return list;
|
15 | 15 | }
|
16 | 16 |
|
17 |
| - private static void permute(int[] nums, List<Integer> temp, List<List<Integer>> list) { |
18 |
| - |
| 17 | + private static void permute1(int[] nums, List<Integer> temp, List<List<Integer>> list) { |
| 18 | + |
19 | 19 | if (temp.size() == nums.length) {
|
20 | 20 | list.add(new ArrayList<>(temp));
|
21 | 21 | return;
|
22 | 22 | }
|
23 |
| - |
| 23 | + |
24 | 24 | for (int i = 0; i < nums.length; i++) {
|
25 | 25 | if (temp.contains(nums[i]))
|
26 | 26 | continue;
|
27 | 27 | temp.add(nums[i]);
|
28 |
| - |
29 |
| - permute(nums, temp, list); |
30 |
| - |
| 28 | + |
| 29 | + permute1(nums, temp, list); |
31 | 30 | temp.remove(temp.size() - 1);
|
32 | 31 | }
|
33 | 32 | }
|
34 | 33 |
|
| 34 | + // O(N!) Time - using visited mark |
| 35 | + public static List<List<Integer>> permute(int[] nums) { |
| 36 | + |
| 37 | + List<List<Integer>> result = new ArrayList<>(); |
| 38 | + boolean[] visited = new boolean[nums.length]; |
| 39 | + |
| 40 | + backtrack(nums, visited, new ArrayList<Integer>(), result); |
| 41 | + |
| 42 | + return result; |
| 43 | + } |
| 44 | + |
| 45 | + private static void backtrack(int[] nums, boolean[] visited, ArrayList<Integer> permutations, |
| 46 | + List<List<Integer>> result) { |
| 47 | + |
| 48 | + if (permutations.size() == nums.length) { |
| 49 | + result.add(new ArrayList<>(permutations)); // deep-copy |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + for (int i = 0; i < nums.length; i++) { |
| 54 | + |
| 55 | + if (visited[i] == true) |
| 56 | + continue; |
| 57 | + |
| 58 | + permutations.add(nums[i]); |
| 59 | + visited[i] = true; |
| 60 | + |
| 61 | + backtrack(nums, visited, permutations, result); |
| 62 | + |
| 63 | + permutations.remove(permutations.size() - 1); // remove recently |
| 64 | + // visited |
| 65 | + visited[i] = false; |
| 66 | + } |
| 67 | + } |
| 68 | + |
35 | 69 | public static void main(String[] args) {
|
36 | 70 | int[] nums = { 1, 2, 3 };
|
37 | 71 | System.out.println(permute(nums));
|
|
0 commit comments