Skip to content

Latest commit

 

History

History
84 lines (69 loc) · 1.33 KB

509.斐波那契数.md

File metadata and controls

84 lines (69 loc) · 1.33 KB

509. 斐波那契数

url

题目

斐波那契数,通常用 F(n) 表示,形成的序列称为 斐波那契数列 。该数列由 01 开始,后面的每一项数字都是前面两项数字的和。也就是:

F(0) = 0,F(1) = 1
F(n) = F(n - 1) + F(n - 2),其中 n > 1
输入:2
输出:1
解释:F(2) = F(1) + F(0) = 1 + 0 = 1
输入:3
输出:2
解释:F(3) = F(2) + F(1) = 1 + 1 = 2
输入:4
输出:3
解释:F(4) = F(3) + F(2) = 2 + 1 = 3

方法

从下往上的思想

code

js

let fib = n => {
    if (n <= 1)
        return n;
    let pre2 = 0, pre1 = 1;
    for (let i = 2; i <= n; i++) {
        let sum = pre2 + pre1;
        pre2 = pre1;
        pre1 = sum;
    }
    return pre1;
};
console.log(fib(2));
console.log(fib(3));
console.log(fib(4));

go

func fib(n int) int {
	if n <= 1 {
		return n
	}
	pre2, pre1 := 0, 1
	for i := 2; i <= n; i++ {
		sum := pre2 + pre1
		pre2 = pre1
		pre1 = sum
	}
	return pre1
}

java

class Solution {
    public int fib(int N) {
        if (N <= 1) return N;
        int pre2 = 0, pre1 = 1;
        for (int i = 2; i <= N; i++) {
            int sum = pre2 + pre1;
            pre2 = pre1;
            pre1 = sum;
        }
        return pre1;
    }
}