-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathPermutations.java
More file actions
56 lines (49 loc) · 1.49 KB
/
Permutations.java
File metadata and controls
56 lines (49 loc) · 1.49 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
55
56
package BackTracking;
import java.util.*;
/*
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
*/
public class Permutations {
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> permutations = new ArrayList<>();
boolean[] seen = new boolean[nums.length];
if(nums == null || nums.length == 0) {
return permutations;
}
findPermutations(nums, permutations, new ArrayList<>(), seen);
return permutations;
}
private void findPermutations (int[] nums, List<List<Integer>> permutations, List<Integer> current, boolean[] seen) {
if(current.size() > nums.length) {
return;
}
if(current.size() == nums.length) {
permutations.add(new ArrayList<>(current));
return;
}
for(int i = 0; i < nums.length; i++) {
if(seen[i] == true) {
continue;
}
current.add(nums[i]);
seen[i] = true;
findPermutations(nums, permutations, current, seen);
current.remove(current.size() - 1);
seen[i] = false;
}
return;
}
}
}