Preview:
/////////////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;
    }
};
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter