Skip to content

Commit c6366ce

Browse files
add a solution for 46
1 parent a962eed commit c6366ce

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,33 @@ private void backtracking(List<Integer> list, int[] nums, Set<List<Integer>> ans
6868
}
6969
}
7070

71+
public static class Solution3 {
72+
/**
73+
* A more efficient version of backtracking.
74+
*/
75+
public List<List<Integer>> permute(int[] nums) {
76+
List<List<Integer>> ans = new ArrayList<>();
77+
boolean[] used = new boolean[nums.length];
78+
return backtracking(ans, used, new ArrayList<>(), nums);
79+
}
80+
81+
private List<List<Integer>> backtracking(List<List<Integer>> ans, boolean[] used, List<Integer> list, int[] nums) {
82+
if (list.size() == nums.length) {
83+
ans.add(new ArrayList<>(list));
84+
return ans;
85+
}
86+
for (int i = 0; i < nums.length; i++) {
87+
if (used[i]) {
88+
continue;
89+
}
90+
used[i] = true;
91+
list.add(nums[i]);
92+
backtracking(ans, used, list, nums);
93+
used[i] = false;
94+
list.remove(list.size() - 1);
95+
}
96+
return ans;
97+
}
98+
}
99+
71100
}

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,26 @@
88
public class _46Test {
99
private static _46.Solution1 solution1;
1010
private static _46.Solution2 solution2;
11+
private static _46.Solution3 solution3;
1112

1213
@BeforeClass
1314
public static void setup() {
1415
solution1 = new _46.Solution1();
1516
solution2 = new _46.Solution2();
17+
solution3 = new _46.Solution3();
1618
}
1719

1820
@Test
1921
public void test1() {
2022
CommonUtils.printListList(solution1.permute(new int[]{1, 2, 3}));
2123
CommonUtils.printListList(solution2.permute(new int[]{1, 2, 3}));
24+
CommonUtils.printListList(solution3.permute(new int[]{1, 2, 3}));
2225
}
2326

2427
@Test
2528
public void test2() {
2629
CommonUtils.printListList(solution1.permute(new int[]{1, 2, 3, 4, 5, 6}));
2730
CommonUtils.printListList(solution2.permute(new int[]{1, 2, 3, 4, 5, 6}));
31+
CommonUtils.printListList(solution3.permute(new int[]{1, 2, 3, 4, 5, 6}));
2832
}
2933
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy