头图

LeetCode-509-Fibonacci Number

雄狮虎豹
中文

Fibonacci number

Title description: Fibonacci number, usually expressed by F(n), the sequence formed is called Fibonacci sequence. The number sequence starts with 0 and 1, and each number after it is the sum of the previous two numbers. That is:

  • F(0) = 0,F(1) = 1
  • F(n) = F(n-1) + F(n-2), where n> 1

Give you n, please calculate F(n).

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/fibonacci-number/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution one: recursive method
When n less than 2, directly return n , when greater than 2, use the formula F(n) = F(n - 1) + F(n - 2) recursively call the current method and return.
Solution 2: Iterative method

When n less than 2, it will return to you directly. When n greater than 2, the current value is calculated by iteration. The specific process is as follows:

  • The value of the first 2 bits of the current value is lastSecond , and the value of the first 1 bit of the current value is lastOne ;
  • Then start traversing from 2 to ;
  • The specific process is lastone updated lastSecond + lastOne , lastSecond updated value before ;

Finally, the value returned by lastOne is the current value.

/**
 * @Author: ck
 * @Date: 2021/10/3 10:33 上午
 */
public class LeetCode_509 {
    /**
     * 递归
     *
     * @param n
     * @return
     */
    public static int fib(int n) {
        if (n < 2) {
            return n;
        }
        return fib(n - 1) + fib(n - 2);
    }

    /**
     * 迭代
     *
     * @param n
     * @return
     */
    public static int fib2(int n) {
        if (n < 2) {
            return n;
        }
        int lastOne = 1, lastSecond = 0;
        for (int i = 2; i <= n; i++) {
            int temp = lastSecond + lastOne;
            lastSecond = lastOne;
            lastOne = temp;
        }
        return lastOne;
    }

    public static void main(String[] args) {
        System.out.println(fib(4));
        System.out.println(fib2(4));
    }
}
[Daily Message] Leave opportunities to friends, luck to relatives, and diligence to yourself.
阅读 477

LeetCodet题解
技术学习

玉树临风,仙姿佚貌!

1.3k 声望
6.1k 粉丝
0 条评论

玉树临风,仙姿佚貌!

1.3k 声望
6.1k 粉丝
文章目录
宣传栏