Do a Fibonacci algorithm problem, result run timeout
public class Solution {public int Fibonacci (int n) { if (n = = 0) { return 0; } if (n = = 1) { return 1; } Return Fibonacci (n-1) + Fibonacci (n-2); }}
Found an article, http://blog.csdn.net/sloder/article/details/8624373
Follow the ideas that they provide:
The value of each item before the calculated item is saved, and the calculation of each item only calls the Fibonacci method once,
The number of times the Fibonacci method is actually called is only n-1, and if n=33, then the Fibonacci method is called only 32 times.
The optimized code is:
1 Public classSolution {2 Public intFibonacci (intN) {3 if(n = = 0) {4 return0;5 }6 if(n = = 1) {7 return1;8 }9 int[] Array =New int[N+1];TenArray[0] = 0; OneARRAY[1] = 1; A for(inti = 2; i < n+1; i++) { -Array[i] = array[i-1] + array[i-2]; - } the returnArray[n]; - } -}
Optimization of the Fibonacci sequence algorithm