-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
54 lines (43 loc) · 1.39 KB
/
Solution.java
File metadata and controls
54 lines (43 loc) · 1.39 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package org.example.problems.permutations;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.example.problems.SolutionInterface;
public class Solution implements SolutionInterface {
@Override
public String getName() {
return "Permutations";
}
@Override
public String getUrl() {
return "https://leetcode.com/problems/permutations/|";
}
public List<List<Integer>> permute(int[] nums) {
result = new ArrayList<>();
Set<Integer> numbersLeft = new HashSet<>();
for (int i: nums) {
numbersLeft.add(i);
}
process(new int[]{}, numbersLeft);
return result;
}
private List<List<Integer>> result = new ArrayList<>();
private void process(int[] mutation, Set<Integer> numbersLeft) {
if (numbersLeft.isEmpty()) {
result.add(Arrays.stream(mutation)
.boxed()
.toList());
return;
}
for (int i: numbersLeft) {
int[] newMutation = new int[mutation.length + 1];
System.arraycopy(mutation, 0, newMutation, 0, mutation.length);
newMutation[mutation.length] = i;
Set<Integer> newSet = new HashSet<>(numbersLeft);
newSet.remove(i);
process(newMutation, newSet);
}
}
}