# 509. Fibonacci Number

Mon Mar 20 2023 18:50:55 GMT+0000 (Coordinated Universal Time)

Saved by @Ranjan_kumar #c++

```/////////////Top-down approach ( recursion+memoization )/////////////
class Solution {
public:

int solve(int n, vector<int> &dp)
{
if(n<=1) return n;
if(dp[n]!=-1) return dp[n];
dp[n]=solve(n-1, dp)+solve(n-2,dp);
return dp[n];
}

int fib(int n) {
vector<int> dp(n+1, -1);
return solve(n, dp);
}
};

/////////////////Bottom-Top approach//////////////////////
class Solution {
public:
int fib(int n) {
if(n<=1) return n;
int dp[n+1];
for(int i=0;i<=n;i++)
{
dp[i]=-1;
}
dp[0]=0;
dp[1]=1;
for(int i=2;i<=n;i++)
{
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
};

///////////////////////Space optimization/////////////////
class Solution {
public:
int fib(int n) {
if(n<=1) return n;
int pr1=0, pr2=1, curr;
for(int i=2;i<=n;i++)
{
curr=pr1+pr2;
pr1=pr2;
pr2=curr;
}
return curr;
}
};```
content_copyCOPY

## Top-down approach ( recursion+memoization ) ## Bottom-Top approach ## Space optimization

https://leetcode.com/problems/fibonacci-number/