Can someone explain this code? Permutation code [closed]

落爺英雄遲暮 提交于 2021-02-05 11:15:13

问题


I am working on a project. I found this code regarding permutations on the Interwebz. I would like to use it as a basis for writing my own code. However, I don't really understand what is going on in the code. Could anybody lend me a hand and explain what the code is doing exactly?

public void permutations(String prefix, String s) {
    int n = s.length();
    if (n == 0)
        System.out.println(prefix);
    else {
        for(int i = 0; i < n; i++){
           permutations(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, n));
        }
    }
}

回答1:


The method permutations is taking in a String prefix and a String s as its parameters. The int type n is being set to the length of the String s. (length of a String being how many characters it contains).

Now we move on to the if-else statements. The if statement is saying, if the length of s is 0, that is, s is a blank String and does not contain any information, then we are simply printing the String prefix instead to the console. The method will then skip over the else part and execute the code after the permutations method.

If the if statement's conditions are not met, we are going to run the else statement is saying, for each character in the String s, we are going to append (add) that character at the end of prefix, so for example, if prefix was originally "hello" and the character was 'U', we would get prefix to be "helloU". After we are finished appending all of the characters in s, we are going to be using the result as the new prefix String.

For the other parameter, the String s, we are going to be taking part of the String, from character 0 (inclusive) to character at position i (exclusive). Please note that the String indexes start at 0 and go up to (The length of the String - 1). We are also taking the part of the String from the character at position i + 1 (inclusive) to the last character in the String s. We are going to use this result as the new s String.

Then we would be calling the method again, and then the method would execute again with the newly defined Strings if the else condition is met. This would continue in a loop until the else condition is not met, at which point the method would stop running and we would move on to the next section of code (if it is present).




回答2:


p(String prefix, String s) takes 1 character out of s and adds it to prefix and recursively continues until s is empty.

The s.charAt(i), s.substring(0, i) + s.substring(i+1, n) part extracts a character from s. Assume s = "Magic!" and i = 3 then charAt(i) = 'i', s.substring(0, i) = "Mag" and s.substring(i+1, n) = c!". That spilts Magic! into i and Magc!. Next time in the loop with i = 4 it will result in c + Magi!. Since it does that for every character in s every character will be in the front in one of the recursive steps.

The call hierarchy would look like this

                                  / p("ab", "c") - "abc"
                 /- p("a", "bc") x
                /                 \ p("ac", "b") - "acb"
               /
              /                   / p("ba", "c") - "bac"
p("", "abc") x ---- p("b", "ac") x
              \                   \ p("bc", "a") - "bca"
               \
                \                 / p("ca", "b") - "cab"
                 \- p("c", "ab") x
                                  \ p("cb", "a") - "cba"

                 ^-- 1st for loop  ^- 2nd for      ^- 3rd one prints



回答3:


permutations(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, n));

Actually, this permutation algorithm is using the idea of

Switching current character with ith character.

Suppose we have a string abc. So the permutation of it is:

abc, acb, bac, bca, cab, cba

We can find that the acb is just switching b and c in abc with prefix a. And the bca is just switching c and a in bac with prefix b.

Then we just use the same idea to recursively solve permutation problem.




回答4:


This is some really confusing code, for two reasons:

  1. The prefix argument: you should call this function with an empty string in the first argument, for example permutations("", "ab") to print all (both) permutations of "ab".
  2. The recursive call with s.substring(0, i) + s.substring(i+1, n) in the second argument: note that java's String.substring(x,y) will not include the y-th character. So this amounts to passing s with the y-th character deleted.

Now think what happens as you step through the for loop: the first argument becomes "" concatenated with "a", i.e. "a", and the second argument becomes s with the first character deleted, i.e. "b". In the next recursive subcall, prefix becomes "ab" and the second argument becomes the empty string "". So the base-case n == 0 gets hit and we print the result "ab".

Now we go to the next iteration of the for loop, i == 1. Now we pass "b" in the first argument of our recursive subcall, and "a" in the second argument. In the next recursive subcall prefix becomes "ba" and s.length is 0, so base case again: print "ba".

It's clever, but inscrutable.



来源:https://stackoverflow.com/questions/13735065/can-someone-explain-this-code-permutation-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!