-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutationExample.java
More file actions
53 lines (47 loc) · 1.53 KB
/
PermutationExample.java
File metadata and controls
53 lines (47 loc) · 1.53 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
package Recursion;
import java.util.ArrayList;
import java.util.List;
/*
46. Permutations
*/
public class PermutationExample {
// Time: O(n^2 * n!)
public static List<List<Integer>> permutationsRecursive(int[] nums) {
return helper(0, nums);
}
public static List<List<Integer>> helper(int i, int[] nums) {
if (i == nums.length) {
List<List<Integer>> res = new ArrayList<>();
res.add(new ArrayList<>());
return res;
}
List<List<Integer>> resPerms = new ArrayList<>();
List<List<Integer>> perms = helper(i + 1, nums);
for (List<Integer> p : perms) {
for (int j = 0; j < p.size() + 1; j++) {
List<Integer> pCopy = new ArrayList<>(p);
pCopy.add(j, nums[i]);
resPerms.add(pCopy);
}
}
return resPerms;
}
// Time: O(n^2 * n!)
public static List<List<Integer>> permutationsIterative(int[] nums) {
List<List<Integer>> perms = new ArrayList<>();
perms.add(new ArrayList<>());
for (int n : nums) {
List<List<Integer>> nextPerms = new ArrayList<>();
for (List<Integer> p : perms) {
for (int i = 0; i < p.size() + 1; i++) {
List<Integer> pCopy = new ArrayList<>();
pCopy.addAll(p);
pCopy.add(i, n);
nextPerms.add(pCopy);
}
}
perms = nextPerms;
}
return perms;
}
}