/* 1st method would lead to time limit */
/* The time complexity is exponential sicne t (n) = t (n-1) + t (n-2) */
Class Solution { /** * @param n:an integer * @return an integer f (n) */public int Fibonacci (int n) { //Write your code here if (n = = 1 | | n = = 2) { return (n-1); } int sum = (n-1) + (n-2); Return Fibonacci (n-1) + Fibonacci (n-2); }}
/* 2nd method would need O (n) space, using DP */
/* T and S are both O (n) */
1 Public intFibonacciintN) {2 //declare an array to store the result3 //It have to is n+2 to avoid out_of_bound4 int[] f =New int[N+2]; 5F[1] = 0;//When input is 1 = zero6F[2] = 1;//When input is 2 = 17 8 inti = 3;9 while(I <= N) {//it has been incremental instead of DecrementalTenF[i] = f[i-1] + f[i-2]; Onei++; A } - - returnF[n]; the}
/* 3rd method would only need O (1) space */
/* We can optimize the space used in method 2 by storing the previous and numbers only */
/* Because that's all we need to get the next Fibannaci number in series. */
1 Public intFibonacciintN) {2 if(N < 3)returnN-1;3 4 intFirst = 0;5 intSecond = 1;6 intThird = 1;7 8 inti = 3;9 while(I <=N) {TenThird = first +second; OneFirst =second; ASecond =third; -i++; - } the returnthird; -}
Lintcode 366 Fibonacci