【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用户