Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 5db9f12

Browse files
add a solution for 46
1 parent 6784784 commit 5db9f12

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/main/java/com/fishercoder/solutions/_46.java

+39
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package com.fishercoder.solutions;
22

33
import java.util.ArrayList;
4+
import java.util.HashSet;
45
import java.util.List;
6+
import java.util.Set;
57

68
public class _46 {
79

@@ -29,4 +31,41 @@ private List<List<Integer>> backtracking(int[] nums, int index, List<List<Intege
2931
}
3032
}
3133

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+
3271
}

src/test/java/com/fishercoder/_46Test.java

+4
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,23 @@
77

88
public class _46Test {
99
private static _46.Solution1 solution1;
10+
private static _46.Solution2 solution2;
1011

1112
@BeforeClass
1213
public static void setup() {
1314
solution1 = new _46.Solution1();
15+
solution2 = new _46.Solution2();
1416
}
1517

1618
@Test
1719
public void test1() {
1820
CommonUtils.printListList(solution1.permute(new int[]{1, 2, 3}));
21+
CommonUtils.printListList(solution2.permute(new int[]{1, 2, 3}));
1922
}
2023

2124
@Test
2225
public void test2() {
2326
CommonUtils.printListList(solution1.permute(new int[]{1, 2, 3, 4, 5, 6}));
27+
CommonUtils.printListList(solution2.permute(new int[]{1, 2, 3, 4, 5, 6}));
2428
}
2529
}

0 commit comments

Comments
 (0)