When I was solving the problem that I wanted to get all the combinations of characters from the given character string, I looked it up and found that chakotay's blog = 612) had what I was looking for !!!
public static void permutation(String q, String ans){
// Base Case
if(q.length() <= 1) {
System.out.println(ans + q);
}
// General Case
else {
for (int i = 0; i < q.length(); i++) {
permutation(q.substring(0, i) + q.substring(i + 1),
ans + q.charAt(i));
}
}
}
I was impressed by the very concise code, even though I searched various things including English !!!
But I don't know what's going on. .. .. Therefore, I would like to look at recursion step by step.
As an example, let's take a look at the behavior of permutation ("abc", "")
in order.
permutation("abc","")
//q.length=3 so go to else
//i=When 0(This i is less than 3)
permutation("bc","a")
//q.length=2 so go to else
//i=When 0(This i is less than 2)
permutation("c","ab")
//q.length=1 so go to if
System.out.println("abc");
//i=When 1(This i is less than 2)
permutation("b","ac")
//q.length=1 so go to if
System.out.println("acb");
//permutation("bc","a") done
//i=When 1(This i is less than 3)
permutation("ac","b")
//q.length=2 so go to else
//i=When 0(This i is less than 2)
permutation("c","ba")
//q.length=1 so go to if
System.out.println("bac");
//i=When 1(This i is less than 2)
permutation("a","bc")
//q.length=1 so go to if
System.out.println("bca");
//permutation("ac","b") done
//i=When 2(This i is less than 3)
permutation("ab","c")
//q.length=2 so go to else
//i=When 0(This i is less than 2)
permutation("b","ca")
//q.length=1 so go to if
System.out.println("cab");
//i=When 1(This i is less than 2)
permutation("a","cb")
//q.length=1 so go to if
System.out.println("cba");
//permutation("ab","c") done
//permutation("abc","") done
It is like this. Is it difficult to understand? I wrote it down and understood it, but I often admired that I couldn't come up with such a method on my own.
that's all. It was my first post.
Recommended Posts