快速斐波那契递归

编程入门 行业动态 更新时间:2024-10-16 20:27:55
本文介绍了快速斐波那契递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图回忆起在斐波那契递归算法。以下内容:

I'm trying to recall an algorithm on Fibonacci recursion. The following:

public int fibonacci(int n) { if(n == 0) return 0; else if(n == 1) return 1; else return fibonacci(n - 1) + fibonacci(n - 2); }

是不可以我在找什么,因为它是贪婪的。这将成倍增长(只是看 Java的递归Fibonacci序列 - 越大的初始参数更没用的电话将进行)。

is not what I'm looking for because it's greedy. This will grow exponentially (just look at Java recursive Fibonacci sequence - the bigger the initial argument the more useless calls will be made).

有可能是有点像循环论证移位,其中调用previous斐波那契价​​值将再次检索计算它的价值吧。

There is probably something like a "cyclic argument shift", where calling previous Fibonacci value will retrieve value instead of calculating it again.

推荐答案

也许是这样的:

int fib(int term, int val = 1, int prev = 0) { if(term == 0) return prev; if(term == 1) return val; return fib(term - 1, val+prev, val); }

此功能是尾递归。这意味着它可以优化和执行非常有效。事实上,它被优化成一个简单的循环。

this function is tail recursive. this means it could be optimized and executed very efficiently. In fact, it gets optimized into a simple loop..

更多推荐

快速斐波那契递归

本文发布于:2023-11-29 20:57:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647608.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   快速

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!