Counting All Line Swaps (Cracking the Coding Interview, Chapter VI - Example 12)

In Gail Laakman's book Hacking the Coding Code, Chapter VI (Big O), Example 12, the problem says that given the following Java code to calculate the permutation of strings, you need to calculate the code complexity

public static void permutation(String str) {
    permutation(str, "");
}

public static void permutation(String str, String prefix) {
    if (str.length() == 0) {
        System.out.println(prefix);
    } else {
        for (int i = 0; i < str.length(); i++) {
            String rem = str.substring(0, i) + str.substring(i + 1);
            permutation(rem, prefix + str.charAt(i));
        }
    }
}

The book assumes that since there will be n! permutations, if we consider each of the permutations as a leaf in the call tree, where each leaf is attached to a path of length n, then there will be no more n * n! nodes in the tree (that is: the number of calls is not more than n * n!).

But there should be no number of nodes:

foo + bar

since the number of calls is equivalent to the number of nodes (look at the figure in the video Line Swap | Quinston Pimenta Code Guide ).

, 1 ( / ) + 3 ( ) + 3 * 2 ( ) + 3 * 2 * 1 ( / )

i.e.: = 3!/3! + 3!/2! + 3!/1! + 3!/0!= 16

, , 3 * 3!= 18

node, ?

+4
2

. , .

e * n! n, O(n!).

- , , n * n!, . , , , .

, node.

. 2 node. 1, 1, n, O(n) .

, n. node. n = 3:

  • 1 node 3 : 1 * 3 = 3
  • 3 2 : 3 * 2 = 6
  • 6 1 : 6 * 1 = 6

: 3 + 6 + 6 = 15. , . node .

, O(n!) , O(n), O(n * n!).

+2

, 3 (ABC), 6 = 3!, 6 1 + 2 + 3. , 4 (ABCD), 4 * 3!, D 1 4. D 3! . , .

n! = str.length()! , 0 n-1. O(n * n!).


-, 0->n-1, 1->n not 0->n.

-, , , . , .

, 4 , 4 * 3! = 24, . 0->n-1 = 0->3 , . , O(n *n!) = O(4 * 4!).

0

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


All Articles