与剑指 Offer 10- I. 斐波那契数列 - 力扣(LeetCode)相同
class Solution {
public:
int fib(int N) {
vector<int> dp(N+1, 0);
dp[0] = 0;
if(N >= 1) dp[1] = 1;
for(int i = 2; i <= N; ++i) dp[i] = dp[i-1] + dp[i-2];
return dp[N];
}
};
空间压缩:
class Solution {
public:
int fib(int N) {
int pre = 0, cur = 1;
if(N < 1) return pre;
for(int i = 2; i <= N; ++i){
int tmp = cur;
cur += pre;
pre = tmp;
}
return cur;
}
};