-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprintAllPossiblePermutations.java
65 lines (58 loc) · 2 KB
/
printAllPossiblePermutations.java
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
57
58
59
60
61
62
63
64
65
import java.util.ArrayList;
import java.util.List;
public class printAllPossiblePermutations {
// public static void permuter(int[] nums, List<Integer> ds, List<List<Integer>> ans, boolean[] freq) {
// if (ds.size() == nums.length) {
// ans.add(new ArrayList<>(ds));
// return;
// }
// for (int i = 0; i < nums.length; i++) {
// if (!freq[i]) {
// freq[i] = true;
// ds.add(nums[i]);
// permuter(nums, ds, ans, freq);
// ds.remove(ds.size() - 1);
// freq[i] = false;
// }
// }
// }
// public static List<List<Integer>> permute(int[] nums) {
// List<List<Integer>> ans = new ArrayList<>();
// List<Integer> ds = new ArrayList<>();
// boolean[] freq = new boolean[nums.length];
// permuter(nums, ds, ans, freq);
// return ans;
// }
// TC: O(N! * N)
// SC: O(N) + O(N) + O(N)
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
permuter(nums, 0, result);
return result;
}
private static void permuter(int[] nums, int start, List<List<Integer>> result) {
if (start == nums.length) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
list.add(nums[i]);
}
result.add(new ArrayList<>(list));
return;
}
for (int i = start; i < nums.length; i++) {
swap(nums, start, i);
permuter(nums, start + 1, result);
swap(nums, start, i);
}
}
public static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4};
List<List<Integer>> result = permute(nums);
System.out.println(result.toString());
}
}