String permutations using recursion in Java

I came across IT , which tried very hard to explain the recursive solution for printing the entire line.

public class Main {
    private static void permutation(String prefix, String str){
        int n = str.length();
        if (n == 0) 
            System.out.println(prefix);
        else {
            for (int i = 0; i < n; i++)
                permutation(prefix + str.charAt(i), 
            str.substring(0, i) + str.substring(i+1));
        }
    }
    public static void main(String[] args) {
        permutation("", "ABCD");
    }
}

But still I can’t get the part when we start popping out of the stack. For example, the recursion goes all the way to the permutation ("ABCD", "), where the base case occurs and prints ABCD. But now what happens? We push the permutation (" ABC "," D ") out of the function call stack. What do we do with this etc.

Maybe someone can help explain a little.

Also, do I need some pointers to the time complexity of this? Not like a complete calculation, but some tips.

+4
1

: permutation("", "ABC"), *:

* ABC + A BC + AB C - ABC *
      |      |
      |      ` AC B - ACB *
      |
      + B AC + BA C - BAC *
      |      |
      |      ` BC A - BCA *
      |
      ` C AB + CA B - CAB *
             |
             ` CB A - CBA *

, , . , . , ("A", "BC"); ("AB", "C") , , ("ABC", ""). . , , , . , ("A", "BC"); "BC" , "B", "C" turn: ("AC", "B"), ("ACB", ""). ("A", "BC") ... , ! ("", "ABC") . , , , " ".

. ( 3 , 2 , ), . , n * (n - 1) * (n - 2) * ... * 2 * 1. O(N!)?

+2

Source: https://habr.com/ru/post/1570557/


All Articles