-
Notifications
You must be signed in to change notification settings - Fork 19.7k
/
Copy pathPermutation.java
57 lines (52 loc) · 1.59 KB
/
Permutation.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
package com.thealgorithms.backtracking;
import java.util.LinkedList;
import java.util.List;
/**
* Finds all permutations of given array
* @author Alan Piao (<a href="https://github.com/cpiao3">Git-Alan Piao</a>)
*/
public final class Permutation {
private Permutation() {
}
/**
* Find all permutations of given array using backtracking
* @param arr the array.
* @param <T> the type of elements in the array.
* @return a list of all permutations.
*/
public static <T> List<T[]> permutation(T[] arr) {
T[] array = arr.clone();
List<T[]> result = new LinkedList<>();
backtracking(array, 0, result);
return result;
}
/**
* Backtrack all possible orders of a given array
* @param arr the array.
* @param index the starting index.
* @param result the list contains all permutations.
* @param <T> the type of elements in the array.
*/
private static <T> void backtracking(T[] arr, int index, List<T[]> result) {
if (index == arr.length) {
result.add(arr.clone());
}
for (int i = index; i < arr.length; i++) {
swap(index, i, arr);
backtracking(arr, index + 1, result);
swap(index, i, arr);
}
}
/**
* Swap two element for a given array
* @param a first index
* @param b second index
* @param arr the array.
* @param <T> the type of elements in the array.
*/
private static <T> void swap(int a, int b, T[] arr) {
T temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}