G
G
gleendo2017-07-12 11:35:38
Java
gleendo, 2017-07-12 11:35:38

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

1 answer(s)
M
Mercury13, 2017-07-12
@Mercury13

One by one for each of the elements.
1. Put it in last place.
2. Call the function recursively with length 1 less.
She, accordingly, will put each of the remaining ones in turn on the PRE-last place, and so on.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question