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;
}