-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations.java
More file actions
32 lines (23 loc) · 1011 Bytes
/
Permutations.java
File metadata and controls
32 lines (23 loc) · 1011 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
26
27
28
29
30
31
32
class Solution {
// Space: O(n!)
// Time complexity: O(n^2*n!)
public List<List<Integer>> permute(int[] nums) {
if (nums.length == 0) {
List<Integer> perm = new LinkedList<Integer>();
List<List<Integer>> perms = new LinkedList<List<Integer>>();
perms.add(perm);
return perms;
}
int[] nums2 = Arrays.copyOfRange(nums, 1, nums.length);
List<List<Integer>> prevPermutations = permute(nums2);
List<List<Integer>> permutations = new LinkedList<List<Integer>>();
for(List<Integer> permutation: prevPermutations) {
for (int i = 0; i <= permutation.size(); i++) {
List<Integer> newPerm = new LinkedList<>(permutation);
newPerm.add(i, nums[0]);
permutations.add(newPerm);
}
}
return permutations;
}
}