【LeetCode】509. Fibonacci Number 斐波那契數(Easy)(JAVA)每日一題
阿新 • • 發佈:2021-01-07
技術標籤:LeetCode 每日一題leetcodejava演算法面試資料結構
【LeetCode】509. Fibonacci Number 斐波那契數(Easy)(JAVA)
題目地址: https://leetcode.com/problems/fibonacci-number/
題目描述:
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.
Example 3:
Input: n = 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
Constraints:
- 0 <= n <= 30
題目大意
斐波那契數,通常用F(n) 表示,形成的序列稱為 斐波那契數列 。該數列由0 和 1 開始,後面的每一項數字都是前面兩項數字的和。也就是:
F(0) = 0,F(1)= 1
F(n) = F(n - 1) + F(n - 2),其中 n > 1
給你 n ,請計算 F(n) 。
解題方法
- 最容易想到的就是用遞迴: F(n) = F(n - 1) + F(n - 2); 遞迴存在的最大問題是會重複計算,比如 F(n) 需要計算一遍 F(n - 2), F(n - 1) 也需要計算一遍 F(n - 2); 就會造成沒必要的重複計算
- 所以採用從上到下的思想,從 0 計算到 n,F(0), F(1) -> F(2) -> F(3) -> … -> F(n)
- 只要用兩個變數儲存先前的兩個值即可
class Solution {
public int fib(int n) {
if (n <= 1) return n;
int pre = 0;
int cur = 1;
for (int i = 2; i <= n; i++) {
int temp = cur;
cur += pre;
pre = temp;
}
return cur;
}
}
執行耗時:0 ms,擊敗了100.00% 的Java使用者
記憶體消耗:35.1 MB,擊敗了73.46% 的Java使用者