Fibonacci

Description

Find the Nth number in Fibonacci sequence.

A Fibonacci sequence is defined as follow:

The first two numbers are 0 and 1. The i th number is the sum of i-1 th number and i-2 th number. The first ten numbers in Fibonacci sequence is:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34...

Notice 
The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.
Example
Given 1, return 0
Given 2, return 1
Given 10, return 34

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
class Solution{
public:
    /**
     * @param n: an integer
     * @return an integer f(n)
     */
    // ----------------------------------------------
    // naive version
    int fibonacci(int n) {
        // write your code here
        vector<int> nums = {0, 0, 1};
        if (n < 3) {
            return nums[n];
        }
        for (int i = 3; i <= n; ++i) {
            nums.push_back(nums[i-2] + nums[i-1]);
        }
        return nums[n];
    }
    // ----------------------------------------------
    // simplified version
    int fibonacci(int n) {
        // write your code here
        vector<int> nums = {0, 0, 1};
        if (n < 3) {
            return nums[n];
        }
        for (int i = 3; i <= n; ++i) {
            int tmp = nums[2];
            nums[2] = nums[1] + nums[2];
            nums[1] = tmp;
        }
        return nums[2];
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""