我在学校里很难理解递归。每当教授谈到它的时候,我似乎都懂了,但当我自己尝试的时候,它完全震撼了我的大脑。

我整晚都在尝试着解决《Towers of Hanoi》这款游戏,结果完全出乎我的意料。我的课本只有大约30页关于递归的内容,所以它不是很有用。有人知道哪些书籍或资源可以帮助澄清这个话题吗?


当前回答

递归函数只是一个函数,它可以根据需要多次调用自己。如果您需要多次处理某件事,但不确定实际需要多少次,那么它就很有用。在某种程度上,你可以把递归函数看作是一种循环。然而,就像循环一样,您需要指定中断流程的条件,否则它将变得无限。

其他回答

http://javabat.com是一个有趣而令人兴奋的练习递归的地方。他们的例子开始时相当简单,然后逐步扩展(如果你想这么做的话)。注意:他们的方法是在实践中学习。这是我写的一个递归函数,用来替换for循环。

for循环:

public printBar(length)
{
  String holder = "";
  for (int index = 0; i < length; i++)
  {
    holder += "*"
  }
  return holder;
}

这是做同样事情的递归。(请注意,我们重载了第一个方法,以确保它像上面那样使用)。我们还有另一种方法来维护索引(类似于上面的for语句)。递归函数必须维护自己的索引。

public String printBar(int Length) // Method, to call the recursive function
{
  printBar(length, 0);
}

public String printBar(int length, int index) //Overloaded recursive method
{
  // To get a better idea of how this works without a for loop
  // you can also replace this if/else with the for loop and
  // operationally, it should do the same thing.
  if (index >= length)
    return "";
  else
    return "*" + printBar(length, index + 1); // Make recursive call
}

简而言之,递归是一种编写更少代码的好方法。在后面的printBar中,请注意我们有一个if语句。如果我们的条件已经达到,我们将退出递归并返回到前一个方法,该方法返回到前一个方法,等等。如果我发送一个printBar(8),我得到********。我希望通过一个简单函数的例子,它做的事情与for循环相同,这可能会有所帮助。不过,您可以在Java Bat中进行更多的练习。

递归函数只是一个函数,它可以根据需要多次调用自己。如果您需要多次处理某件事,但不确定实际需要多少次,那么它就很有用。在某种程度上,你可以把递归函数看作是一种循环。然而,就像循环一样,您需要指定中断流程的条件,否则它将变得无限。

这与其说是一个问题,不如说是一个抱怨。关于递归你有更具体的问题吗?就像乘法一样,人们不会写很多关于它的东西。

说到乘法,想想这个。

问题:

* b是什么?

答:

如果b = 1,就是a。 否则就是a+a*(b-1)

* (b - 1)是什么?请参考上面的问题来解决这个问题。

Common Lisp中的简单递归示例:

MYMAP对列表中的每个元素应用一个函数。

1)空列表没有元素,所以我们返回空列表-()和NIL都是空列表。

2)将函数应用到第一个列表,对列表的其余部分调用MYMAP(递归调用),并将两个结果合并到一个新列表中。

(DEFUN MYMAP (FUNCTION LIST)
  (IF (NULL LIST)
      ()
      (CONS (FUNCALL FUNCTION (FIRST LIST))
            (MYMAP FUNCTION (REST LIST)))))

让我们观察跟踪执行。在输入函数时,输出参数。在退出函数时,输出结果。对于每个递归调用,输出将按级别缩进。

这个例子对列表(1 2 3 4)中的每个数字调用SIN函数。

Command: (mymap 'sin '(1 2 3 4))

1 Enter MYMAP SIN (1 2 3 4)
| 2 Enter MYMAP SIN (2 3 4)
|   3 Enter MYMAP SIN (3 4)
|   | 4 Enter MYMAP SIN (4)
|   |   5 Enter MYMAP SIN NIL
|   |   5 Exit MYMAP NIL
|   | 4 Exit MYMAP (-0.75680256)
|   3 Exit MYMAP (0.14112002 -0.75680256)
| 2 Exit MYMAP (0.9092975 0.14112002 -0.75680256)
1 Exit MYMAP (0.841471 0.9092975 0.14112002 -0.75680256)

这是我们的结果:

(0.841471 0.9092975 0.14112002 -0.75680256)

Ouch. I tried to figure out the Towers of Hanoi last year. The tricky thing about TOH is it's not a simple example of recursion - you have nested recursions which also change the roles of towers on each call. The only way I could get it to make sense was to literally visualize the movement of the rings in my mind's eye, and verbalize what the recursive call would be. I would start with a single ring, then two, then three. I actually ordered the game on the internet. It took me maybe two or three days of cracking my brains to get it.