Answer the question
In order to leave comments, you need to log in
How to understand the solution of the problem of finding all anagrams (recursion)?
There is a recursive solution to the problem of finding all anagrams.
Please help me figure out the solution. Over a long time I sit, I can not figure out what's what.
import java.util.Arrays;
public class Permutator {
public static void perm(int[] arr, int size){
if( size < 2){
System.out.println(Arrays.toString(arr));
} else {
for (int i = 0; i < size; k++){
swap(arr, i, size - 1);
perm(arr, size - 1);
swap(arr, i, size - 1); // *
}
}
}
private static void swap(int [] arr, int a, int b){
int tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
}
// Input - [1, 2, 3]
// ---------------------------------------------------
// size не меньше 2.
// Заходим в цикл. i = 0, size = 3
// Делаем обмен нулевого элемента с size - 1 элементом. Получаем [3, 2, 1]
// Вызываем опять perm([3, 2, 1], 2);
// size не меньше 2.
// Заходим в цикл. i = 0, size = 2
// Делаем обмен нулевого элемента с size - 1 элементом. Получаем [2, 3, 1]
// Вызываем опять perm([2, 3, 1], 1);
// size меньше 2
// Выводим массив [2, 3, 1]
// ---------------------------------------------------
// Что дальше идет?
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question