递归问题:修订
我的幻灯片说:
递归调用应始终在比当前数据结构更小的数据结构上
必须有一个非如果数据结构太小,则采用递归选项
您需要一个包装方法来使递归方法可访问
仅从幻灯片中阅读此内容是没有意义的,特别是考虑到这是圣诞节前的主题!
有人可以尝试弄清楚这意味着什么吗?
谢谢
My slides say that:
A recursive call should always be on a smaller data structure than the current one
There must be a non recursive option if the data structure is too small
You need a wrapper method to make the recursive method accessible
Just reading this from the slides makes no sense, especially seeing as it was a topic from before christmas!
Could anyone try and clear up what it means please?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,这是不正确的,但如果您正在谈论带有递归的链表操作,则事实如此。这意味着您需要始终努力寻求解决方案,而这通常是在处理比开始时更小的问题。
以快速排序为例。每次调用该函数时,它都会处理较小的数据集。
再举一个打印链表的例子,下次调用递归函数时,参数应该是链表的尾部(这段代码有一个错误,但这引导我们到下一点)
这意味着应该有一个基本情况。函数再次停止调用自身的点。
回到打印链接列表的示例,必须有一种情况,您只剩下一个空列表(在这种情况下,该函数应该不执行任何操作)。回到打印链表的代码
我不懂Java,而且它并不是真正为递归设计的语言,但是在许多情况下,你的递归函数将具有比使用API的人应该能够承受的参数更多的参数查看。例如,您可能希望在那里有一个柜台。
您可以拥有一个包装函数,将参数简化为所需的参数。然后包装函数调用真正的工作函数。
一个例子是,如果我们有一个链表类,它具有打印列表的递归函数。它的声明看起来像这样:
然而,由于它是一个类方法,对于使用 API 的人来说,这样做没有多大意义:
因此可以创建一个没有任何参数的包装函数,然后调用完成工作的代码。
那么使用 API 的程序员所要做的就是:
In general this isn't true but if you are talking about linked lists manipulation with recursion it is. What it is implying is that you need to always be working towards a solution and this usually is dealing with a smaller problem than you started with.
Take for example Quicksort. Each time the function is called it is working with a smaller set of data.
Taking another example of printing a linked list, the next time you call the recursive function the argument should be the tail of the linked list (This code has an error in it, but that leads us to our next point)
This means there should be a base case. The point where the function stops calling itself again.
Going back to the example of printing a linked list, there has to be a case where you only have an empty list left (in which case the function should do nothing). Going back to the code to print a linked list
I don't know Java, and it isn't really a language designed for recursion, however in many cases your recursive function will have more parameters than the person using the API should be able to see. You might for example want to have a counter in there.
You can have a wrapper function that simplifies the parameters to just what is needed. The wrapper function then calls the real worker function.
An example might be if we have a linked list class that has the recursive function to print the list. Its declaration would look something like this:
However as it is a class method, to someone using the API it doesn't make much sence to have to do this:
So a wrapper function could be created that doesn't have any paramters which then calls the code that does the work.
Then all the programmer using the API has to do is: