我是递归的新手,我仍然对这个问题感到困惑。
这是代码
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()
}
所以答案就是:
YesYes1Yes12Yes123End
问题是为什么当我将回报切换为
时,“结束”首先打印 return Recurse(s + n, n + 1) + s;
注意s现在是递归后的
结果如下:
EndYes123Yes12Yes1Yes
答案 0 :(得分:1)
“结束”放置在评估字符串最后一部分的位置。当您执行s + recurse
时,最后一部分将被评估。执行recurse + s
时,最后评估开始。
答案 1 :(得分:1)
让我们抓住虚拟纸并解决这个问题:
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
答案 2 :(得分:1)
请注意,递归最好在树结构中可视化(所谓的递归树)。您通常有终端(在您的情况下,s
)和非终端(进一步的函数调用,即Recurse
)。使用draw.io(网站),我快速创建了这个图,用于说明Recurse(s + n, n + 1) + s
:
您始终从左到右进行评估。要了解如果在每一步切换终端和非终端的顺序会发生什么:垂直镜像,然后再从左到右进行评估。