Lintcode 366 Fibonacci

Source: Internet
Author: User
Tags lintcode

/* 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.