Array: Fibonacci number

Title Description

We all know that Fibonacci number, and now asked to enter an integer n, you output the n-th Fibonacci number Fibonacci sequence of item (from 0, the first 0 is 0).

n<=39

Ideas analysis

公式:
f(n) = n, n <= 1
f(n) = f(n-1) + f(n-2), n > 1

Reference Code

 1 public class Solution {
 2     public int Fibonacci(int n) {
 3         if(n == 0 || n == 1) {
 4             return n;
 5         }
 6         int fn1 = 0;
 7         int fn2 = 1;
 8         for(int i = 2; i <= n; i++) {
 9             fn2 = fn1 + fn2;
10             fn1 = fn2 - fn1;
11         }
12         return fn2;
13     }
14 }

 

Guess you like

Origin www.cnblogs.com/carry6/p/11517080.html