Fibonacci number Java implementation [to prove safety offer]

topic

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

answer

1. recursive

When implemented using a recursive manner, when the n-th node recursively downward from duplicate node n when the larger, slower recursion, is often beyond the time limit required by the subject

2. Non-recursive

description

To avoid double counting, top-down manner calculated

code

public class Solution {
    public int Fibonacci(int n) {
        int first=0;
        int second=1;
        int res=0;
        int[] result={0,1};
        if(n<2){
            return result[n];
        }
        for(int i=1;i<n;i++){
            res=first+second;
            first=second;
            second=res;
        }
        return res;
    }
}

Guess you like

Origin www.cnblogs.com/ERFishing/p/11844629.html
Recommended