当前位置:网站首页>leetcode 509. Fibonacci Number(斐波那契数字)

leetcode 509. Fibonacci Number(斐波那契数字)

2022-07-07 02:17:00 蓝羽飞鸟

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given n, calculate F(n).

Example 1:

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

Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

著名的Fibonacci数字,F(0)=0, F(1)=1,
后面依次是前两个数字的和,求第n个Fibonacci数字。

思路
DP
可以用一维数组记录下0~n个Fibonacci数字,然后第i个数字就是F(i-2)+F(i-1),
但是因为只用到前两个,所以只需要用两个数字保存就行了。

public int fib(int n) {
    
    if(n == 0) return 0;
    if(n == 1) return 1;
    
    int n1 = 0;
    int n2 = 1;
    for(int i = 2; i <= n; i ++) {
    
        int tmp = n1 + n2;
        n1 = n2;
        n2 = tmp;
    }
    
    return n2;
}
原网站

版权声明
本文为[蓝羽飞鸟]所创,转载请带上原文链接,感谢
https://blog.csdn.net/level_code/article/details/125632842