Creating (or printing) permutations of an array is much simpler as a combination of recursively and iteratively than purely iteratively. Of course, there are iterative ways to do this, but it is especially easy with a combination. In particular, note that, by definition, N! permutations of an array of length N - N options for the first slot, selection of N-1 for the second, etc. etc. Thus, we can split the algorithm into two steps for each index i in the array.
- Select the element in the
arr[i....end] ith as the ith element of the array. Change this item with the item currently on arr[i] . - Rearrange
arr[i+1...end] recursively.
Note that this will work in O (N!), Since N subheadings will be made on the first call, each of which will do N-1 sub-elections, etc. etc. In addition, each element will be in each position, and until only swaps are executed, no element will be duplicated.
public static void permute(int[] arr){ permuteHelper(arr, 0); } private static void permuteHelper(int[] arr, int index){ if(index >= arr.length - 1){ //If we are at the last element - nothing left to permute //System.out.println(Arrays.toString(arr)); //Print the array System.out.print("["); for(int i = 0; i < arr.length - 1; i++){ System.out.print(arr[i] + ", "); } if(arr.length > 0) System.out.print(arr[arr.length - 1]); System.out.println("]"); return; } for(int i = index; i < arr.length; i++){ //For each index in the sub array arr[index...end] //Swap the elements at indices index and i int t = arr[index]; arr[index] = arr[i]; arr[i] = t; //Recurse on the sub array arr[index+1...end] permuteHelper(arr, index+1); //Swap the elements back t = arr[index]; arr[index] = arr[i]; arr[i] = t; } }
Example input, output:
public static void main(String[] args) { permute(new int[]{1,2,3,4}); } [1, 2, 3, 4] [1, 2, 4, 3] [1, 3, 2, 4] [1, 3, 4, 2] [1, 4, 3, 2] [1, 4, 2, 3] [2, 1, 3, 4] [2, 1, 4, 3] [2, 3, 1, 4] [2, 3, 4, 1] [2, 4, 3, 1] [2, 4, 1, 3] [3, 2, 1, 4] [3, 2, 4, 1] [3, 1, 2, 4] [3, 1, 4, 2] [3, 4, 1, 2] [3, 4, 2, 1] [4, 2, 3, 1] [4, 2, 1, 3] [4, 3, 2, 1] [4, 3, 1, 2] [4, 1, 3, 2] [4, 1, 2, 3]