509. Fibonacci Number
- Recursion
class Solution {
public:
int fib(int n)
{
if(n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
};
-
T:
-
S:
-
DP
class Solution {
public:
int fib(int n)
{
if(n < 2) return n;
vector<int> dp(n + 1);
dp[0] = 0, dp[1] = 1;
for(int i = 2; i < n + 1; i++)
{
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
};
- T:
- S:
DP improved
class Solution {
public:
int fib(int n)
{
if(n < 2) return n;
int first = 1, second = 1;
for(int i = 2; i < n; i++)
{
int temp = first;
first = first + second;
second = temp;
}
return first;
}
};
- T:
- S: