[英]Can anyone tell me how is this code working?
I can't figure out how this recursion problem works.我无法弄清楚这个递归问题是如何工作的。
I can only get to the point where it prints "teal" after that I get lost.在我迷路之后,我只能到达它打印“蓝绿色”的地步。
class Anagrams {
private static void printAnagramsHelper(String prefix, String word) {
if (word.length() <= 1) {
System.out.println(prefix + word);
} else {
printAnagramsHelper(
prefix + word.charAt(0),
word.substring(1)
);
for (int i = 1; i <= word.length() - 2; i++) {
printAnagramsHelper(
prefix + word.charAt(i),
word.substring(0, i) + word.substring(i + 1)
);
}
printAnagramsHelper(
prefix + word.charAt(word.length() - 1),
word.substring(0, word.length() - 1)
);
}
}
public static void printAnagrams(String word) {
printAnagramsHelper("", word);
}
public static void main(String[] args) {
printAnagrams("teal");
}
}
Output is correct but cant figure out how did it come. Output 是正确的,但无法弄清楚它是怎么来的。
The “prefix” is the result built so far, and “word” is the pool of letters to add the prefix. “prefix”是到目前为止构建的结果,“word”是添加前缀的字母池。
The terminating case is when there are no more letters in “word”, so the result (“prefix”) is printed and recursion stops.终止情况是“word”中没有更多字母,因此打印结果(“prefix”)并且递归停止。
There are three ways of recursing:递归的三种方式:
The code is the java implementation of the above description.代码就是上面描述的java实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.