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
Input: 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
Leetcode 509 斐波那契数(真拗口)
如果只是照着公式写就太暴力了,考虑用动态规划,用一个表来存储已经计算过的值,这样在计算下一个值的时候直接用就好了。
class Solution {
public:
int fib(int N) {
if(N<2) return N;
vector<int> table(N+1);//vector初始化不是[],而是()
table[0] = 0;
table[1] = 1;
for(int i=2;i<N+1;i++){
table[i]=table[i-2]+table[i-1];
}
return table[N];
}
};