packagecom.thealgorithms.backtracking;importjava.util.Arrays;importjava.util.LinkedList;importjava.util.List;publicclassPermutation{/**
* Find all permutations of given array using backtracking
* @param arr the array.
* @param the type of elements in the array.
* @return a list of all permutations.
*/publicstatic<T>List<T[]>permutation(T[] arr){T[] array = arr.clone();List<T[]> result =newLinkedList<>();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 the type of elements in the array.
*/privatestatic<T>voidbacktracking(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 the type of elements in the array.
*/privatestatic<T>voidswap(int a,int b,T[] arr){T temp = arr[a];
arr[a]= arr[b];
arr[b]= temp;}}