Skip to main content

509. Fibonacci Number

  • Recursion
class Solution {
public:
int fib(int n)
{
if(n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
};
  • T: O(2N)O(2^N)

  • S: O(N)O(N)

  • 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: O(N)O(N)
  • S: O(N)O(N)

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: O(N)O(N)
  • S: O(1)O(1)