-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathPermutations.java
More file actions
25 lines (24 loc) · 840 Bytes
/
Permutations.java
File metadata and controls
25 lines (24 loc) · 840 Bytes
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
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Set<Integer> visited = new HashSet<>();
permute(nums, result, new ArrayList<>(), visited);
return result;
}
private void permute(int[] nums, List<List<Integer>> result, List<Integer> curr, Set<Integer> visited) {
if (curr.size() == nums.length) {
result.add(new ArrayList<>(curr));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited.contains(nums[i])) {
continue;
}
visited.add(nums[i]);
curr.add(nums[i]);
permute(nums, result, curr, visited);
visited.remove(nums[i]);
curr.remove(curr.size() - 1);
}
}
}