且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java程序Fibonacci序列

更新时间:2022-03-06 00:00:34

问题是因为你是使用简单递归,您可以多次重新评估F(n),因此执行时间是指数级的。

The problem is that because you are using simple recursion, you re-evaluate F(n) multiple times, so your execution time is exponential.

有两种简单的方法可以解决这个问题:

There are two simple ways to fix this:

1)第一次评估F(n)时的缓存值。在评估F(n)之前先检查缓存,看看你是否已经为此计算了它。

1) Cache values of F(n) when they are evaluated the first time. Check the cache first before evaluating F(n) to see if you have already calculated it for this n.

2)使用迭代方法:计算F(1), F(2),F(3)等......直到达到你需要的数字。

2) Use an iterative approach: Calculate F(1), F(2), F(3), etc... until you reach the number you need.