- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我们遇到了经典的 Hanoi 问题,我刚刚开始研究这个递归问题,这真是太棒了!这是完全正常的,但我只是不明白它怎么可能!据我了解,对于任何 n,它都会打印“from +”到“+ thru”,每次 n 接近 1 时都会发生这种情况。人们会认为在 n=1 时,代码会停止,但是我得到了“thru +”到“+ to”(最后的打印输出)的打印输出。如果 n=1 是终止条件,我怎么可能“免费”获得代码的最后一部分?
我还希望代码至少在每次迭代时执行最后的打印输出,但是没有!此外,这方面的示例总是包括两个递归调用,但只用一个就可以正常工作!这到底是怎么回事?这段代码是如何一步步执行的?我是否误解了有关递归方法的一些基本事实? (在 Eclipse 编译器上编译)。
public static void hanoi(char from, char to, char thru, int n) {
if (n==1) {
System.out.println(from + " going to " + to);
} else {
System.out.println (from + " going to " + thru);
hanoi(from, to, thru, n-1);
System.out.println (thru + " going to " + to);
}
}
最佳答案
Have I misunderstood some basic fact about recursive methods?
听起来你有。您似乎有这样的印象,即使您多次调用该方法,该方法也只退出一次。事实上,每次你点击这条线时:
System.out.println (from + " going to " + thru); <-- this line
hanoi(from, to, thru, n-1);
System.out.println (thru + " going to " + to);
...您还必须在递归调用完成后的某个时刻点击后面的行:
System.out.println (from + " going to " + thru);
hanoi(from, to, thru, n-1);
System.out.println (thru + " going to " + to); <-- this line
n == 1
是“终止条件”,因为它不会进行额外的递归调用。但是,您的“if”语句中仍然包含代码:
if (n==1) {
System.out.println(from + " going to " + to);
}
此代码将作为最终条件的一部分运行,但不会再次调用 hanoi
方法。但是,这只是递归调用的结束。在此之前每次调用 hanoi
时,堆栈上仍有一个方法调用,这些方法调用需要完成。
System.out.println (from + " going to " + thru);
hanoi(from, to, thru, n-1); <-- if `n-1` here was `1`, you'd still have to
complete the following line.
System.out.println (thru + " going to " + to);
关于java - 汉诺塔,工作但不应该,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22900288/
这是我正在做的作业。我创建了 2 个类来玩汉诺塔。第一个基本上是运行实际游戏类的运行者。 import java.util.Scanner; class TowersRunner { publ
这是我为汉诺塔问题编写的 Python 代码,其中塔必须从左桩转移到中间桩,使用右桩作为备用: def hanoi(n, origin = "1", destination = "2", spare
我正在使用 jQuery 标签!库创建用户“技能”输入表单。我认为这将是一个非常快速和简单的设置,就像大多数 jQuery 库一样,但是我在这个方面遇到了很多麻烦。我尝试按照下面示例中的源代码进行操作
我如何(如果可能)使用 C++11 可变参数编程来定义一系列 vector是在一个函数体内,(或者换句话说,一系列 N 维数组,递减 N 直到 0),就像下面的变量一样? vector>> v; ve
我编写了一个 Ansible playbook,它需要运行它的作业编号作为其参数之一,以便我将对该作业的引用添加到我维护的数据库中。如何获取 Tower 模板以将其传递给剧本? 这是我当前的解决方案,
默认情况下,android 会存储最后 200 个 wifi 连接和 50 个单元位置详细信息。 我使用 WifiManager 中的 getConfiguredNetworks() 获得了 wifi
如何(如果可能)使用 c++11 可变参数编程来定义一系列 vector 's 在函数体中,(或者换句话说,N 维数组的序列,N 's 递减直到 0),就像下面的变量? vector>> v; vec
我们正在 Tensorflow 上运行多 GPU 作业,并评估从基于队列的模型(使用 string_input_producer 接口(interface))到新的 Tensorflow 数据集 AP
我有一个由另一个进程启动的 Ansible 作业。现在我需要检查 Ansible Tower 中当前正在运行的作业的状态。 我可以使用 REST API 使用 /jobs/{id} 跟踪状态是否正在运
我正在使用一个非常棒的插件,名为 jQuery Tagit在我当前项目的开发中。 一切都进行得很顺利(令人怀疑),直到我尝试添加自己的一小部分 jQuery。我的目标是让最终用户可以选择使用按钮添加标
我是一名优秀的程序员,十分优秀!