让我们抓住虚拟纸并解决这个问题:
public class TestRecursion {
public static void main(String[] a) {
System.out.println(Recurse("Yes", 1));
}
public static String Recurse(String s, int n) {
if (n < 5)
return s+Recurse(s + n, n + 1);
else
return "End";
} // end Recurse()
}
好的,现在从头开始:
n S s+Recurse(s+n, n+1)
1 Yes "Yes" + Recurse ("Yes1", 2)
2 Yes1 "Yes1" + Recurse ("Yes12", 3)
3 Yes12 "Yes12" + Recurse ("Yes123", 4)
4 Yes123 "Yes123" + Recurse ("Yes1234", 5)
5 Yes1234 "End" <- Here we go to the else block
因此,当我们展开堆栈时,我们得到:
n S s+Recurse(s+n, n+1)
5 Yes1234 "End" <- Here we go to the else block
4 Yes123 "Yes123" + "End"
3 Yes12 "Yes12" + "Yes123End"
2 Yes1 "Yes1" + "Yes12Yes123End"
1 Yes "Yes" + "Yes1Yes12Yes123End"
所以,我们最终得到YesYes1Yes12Yes123End
现在,让我们改变方法:
public class TestRecursion {
public static void main(String[] a) {
System.out.println(Recurse("Yes", 1));
}
public static String Recurse(String s, int n) {
if (n < 5)
return Recurse(s + n, n + 1) + s;
else
return "End";
} // end Recurse()
}
好的,现在从头开始:
n S Recurse(s+n, n+1) + s
1 Yes Recurse ("Yes1", 2) + "Yes"
2 Yes1 Recurse ("Yes12", 3) + "Yes1"
3 Yes12 Recurse ("Yes123", 4) + "Yes12"
4 Yes123 Recurse ("Yes1234", 5) + "Yes123"
5 Yes1234 "End" <- Here we go to the else block
现在,当我们展开堆栈时,我们最终得到:
n S Recurse(s+n, n+1) + s
5 Yes1234 "End" <- Here we go to the else block
4 Yes123 "End" + "Yes123"
3 Yes12 "EndYes123" + "Yes12"
2 Yes1 "EndYes123Yes12" + "Yes1"
1 Yes "EndYes123Yes12Yes1" + "Yes"
所以,我们终于得到EndYes123Yes12Yes1Yes