LintCode 366 Fibonacci

來源:互聯網
上載者:User

標籤:and   ace   declare   ext   ntc   pac   class   pre   one   

/* 1st method will 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 will need O(n) space, using DP */
/* T and S are both O(n) */

 1 public int fibonacci(int n) { 2         // declare an array to store the result 3         // it has to be n+2 to avoid out_of_bound 4         int[] f = new int[n+2];  5         f[1] = 0; // when input is 1 => zero 6         f[2] = 1; // when input is 2 => 1 7          8         int i = 3; 9         while (i <= n) { // it has to be incremental instead of decremental10             f[i] = f[i-1] + f[i-2];11             i++;12         }13         14         return f[n];15     }

 

/* 3rd method will only need O(1) space */
/* We can optimize the space used in method 2 by storing the previous two numbers only */
/* because that is all we need to get the next Fibannaci number in series. */

 1 public int fibonacci(int n) { 2     if (n < 3) return n-1; 3       4     int first = 0; 5     int second = 1; 6     int third = 1; 7      8     int i = 3; 9     while (i <= n) {10         third = first + second;11         first = second;12         second = third;13         i++;14     }15     return third;16 }

 

LintCode 366 Fibonacci

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.