-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutations-ii.java
More file actions
32 lines (25 loc) · 1.08 KB
/
Copy pathpermutations-ii.java
File metadata and controls
32 lines (25 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.*;
class Solution {
public List<List<Integer>> permuteUnique(int[] numbers) {
List<List<Integer>> permutations = new ArrayList<>();
Arrays.sort(numbers); // Sort to handle duplicates
generate(permutations, new ArrayList<>(), numbers, new boolean[numbers.length]);
return permutations;
}
private void generate(List<List<Integer>> permutations, List<Integer> currentList, int[] numbers, boolean[] isUsed) {
if (currentList.size() == numbers.length) {
permutations.add(new ArrayList<>(currentList));
return;
}
for (int index = 0; index < numbers.length; index++) {
if (isUsed[index]) continue;
// Skip duplicate elements
if (index > 0 && numbers[index] == numbers[index - 1] && !isUsed[index - 1]) continue;
isUsed[index] = true;
currentList.add(numbers[index]);
generate(permutations, currentList, numbers, isUsed);
isUsed[index] = false;
currentList.remove(currentList.size() - 1);
}
}
}