问题
I came across THIS post which tried very hard to explain the recursive solution to print all string.
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 am not able to get the part when we start popping off the stack. For example, recursion goes all the way till permutation("ABCD",""), where base case meets and it prints ABCD. But what happens now ? we pop off permutation("ABC","D") from function call stack .. what we do with this and so on.
Can someone please help explain a bit.
Also, I need some pointers on the time complexity of this ? Not like complete calculation but some hints.
回答1:
Easier example: permutation("", "ABC")
, representing empty string as *
:
* 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 *
Note that this looks like a tree laid on its side. Indeed, it called a tree. When we start, we will enter ("A", "BC")
state; we proceed to call ("AB", "C")
, and finally ("ABC", "")
. Here we print our output. Then we remember we have unfinished business, we return to a loop, but the loop in the previous level only had one cycle. So we're done there as well, and return back to ("A", "BC")
level; there are two elements in "BC"
and we've only done the "B"
, so it's now "C"
's turn: we call ("AC", "B")
, which then calls ("ACB", "")
. Now all the loops under ("A", "BC")
are done... But wait, still work to do! Because ("", "ABC")
still has two more letters to process. And so it goes, branch by branch, in what we usually call "depth-first search".
In each level is a loop. The loop shrinks (we iterate 3 times in the thick branch at the left, then 2 in the next level, then only one) but still there is a loop. So in total, we do n * (n - 1) * (n - 2) * ... * 2 * 1
iterations. O(N!)
?
来源:https://stackoverflow.com/questions/27856306/string-permutations-using-recursion-in-java