I solved the problem presented here: https://www.youtube.com/watch?v=PJCgFbb_qWA&list=PLoij6udfBncjOlB-3LfW9kVPAjr1-fqx9&index=4 with help in the comments))))) I do not fully understand what is happening. Please explain. The task was to add the code so that it correctly compiled the "Anagrams", saving the idea. I do not understand how this line (decision) saved the situation, why and how this is explained by the fact that the movement is going back along the stack.

Source:

import java.util.Arrays; public class Permutator { public static void permute (int[] arr, int size){ if( size < 2){ System.out.println(Arrays.toString(arr)); } else { for (int k = 0; k < size; k++){ swap(arr, k, size-1); permute(arr, size-1); } } } private static void swap(int [] arr, int index0, int index1 ){ int tmp = arr[index0]; arr[index0] = arr[index1]; arr[index1] = tmp; } } 

Total (with source array [1, 2, 3]):
[2, 3, 1]
[2, 3, 1]
[1, 2, 3]
[1, 2, 3]
[2, 1, 3]
[2, 1, 3]

Code (the one with the comment is the solution):

 package chapterfirst; import java.util.Arrays; public class Permutator { public static void permute (int[] arr, int size){ if( size < 2){ System.out.println(Arrays.toString(arr)); } else { for (int k = 0; k < size; k++){ swap(arr, k, size-1); permute(arr, size-1); swap(arr, k, size-1); //решение } } } private static void swap(int [] arr, int index0, int index1 ){ int tmp = arr[index0]; arr[index0] = arr[index1]; arr[index1] = tmp; } } 

Result (with source array [1, 2, 3]):
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
[1, 3, 2]
[2, 1, 3]
[1, 2, 3]

    1 answer 1

    Better explain by induction.

    If size is 1 element, the method will print an array.

    If 2 - we take the first element and swap it with the second, and try to repeat the same thing, but already on the subarray of length 1. Here we got case 1.

    If N, then the following will occur, in turn, we will get elements from the array from indexes from 0 to N, interchange them with the last element and call a similar procedure, but on a subarray of size N-1. After the call, we return the items to their original places.