-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPermutations.java
More file actions
51 lines (33 loc) · 1.09 KB
/
Copy pathPermutations.java
File metadata and controls
51 lines (33 loc) · 1.09 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
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Permutations {
public static void swap(int[] nums, int prev, int next) {
int temp = nums[prev];
nums[prev] = nums[next];
nums[next] = temp;
}
public static void permuteRec(int[] nums, int n, List<List<Integer>> output) {
if (n == 1) {
List<Integer> temp = new ArrayList<>();
for (int num : nums) {
temp.add(num);
}
output.add(temp);
} else {
for (int i = 0; i < n; i++) {
swap(nums, i, n - 1); //remove the ith element
permuteRec(nums, n -1, output);
swap(nums, i, n - 1); //restore for next round
}
}
}
public static void permute(int[] nums) {
List<List<Integer>> output = new ArrayList<List<Integer>>();
permuteRec(nums, nums.length, output);
System.out.println(output.toString());
}
public static void main(String[] args) {
permute(new int[]{1, 2, 3});
}
}