当前位置:网站首页>Fibonacci number of leetcode

Fibonacci number of leetcode

2020-11-14 10:41:27 codecraft

order

This article mainly records leetcode Fibonacci number

subject

 Fibonacci number , Usually use  F(n)  Express , The sequence formed is called Fibonacci series . The sequence is composed of  0  and  1  Start , Each of the following numbers is the sum of the first two numbers . That is to say :

F(0) = 0,   F(1) = 1
F(N) = F(N - 1) + F(N - 2),  among  N > 1.
 Given  N, Calculation  F(N).

 

 Example  1:

 Input :2
 Output :1
 explain :F(2) = F(1) + F(0) = 1 + 0 = 1.
 Example  2:

 Input :3
 Output :2
 explain :F(3) = F(2) + F(1) = 1 + 1 = 2.
 Example  3:

 Input :4
 Output :3
 explain :F(4) = F(3) + F(2) = 2 + 1 = 3.
 

 Tips :

0 ≤ N ≤ 30


 source : Power button (LeetCode)
 link :https://leetcode-cn.com/problems/fibonacci-number
 Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Answer key

class Solution {
    public int fib(int N) {
        if(N==0 ||N==1) {
            return N;
        }
        int fn0 = 0;
        int fn1 = 1;
        for (int i=2; i<=N; i++) {
            int tmp = fn0 + fn1;
            fn0 = fn1;
            fn1 = tmp;
        }
        return fn1;
    }
}

Summary

Here we use the formula method to calculate ,F(0) = 0, F(1) = 1, stay N>1 when ,F(N) = F(N - 1) + F(N - 2).

doc

版权声明
本文为[codecraft]所创,转载请带上原文链接,感谢