LeetCode 509. 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.
method 1: 递归
int fib(int n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
method 2: 动态规划
int fib(int n) {
if (n < 2) return n;
vector<int> dp(n + 1);
dp[1] = 1;
for (int i = 2; i < n + 1; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
可以只用2个变量
int fib(int n) {
if (n < 2) return n;
int dp0 = 0;
int dp1 = 1;
for (int i = 2; i <= n; i++) {
int res = dp0 + dp1;
dp0 = dp1;
dp1 = res;
}
return dp1;
}