From f98914fb299e105c24ab3f6f5d9624c5aeb97cdb Mon Sep 17 00:00:00 2001 From: Vatsalya Gupta <64428075+vatsalya-gupta@users.noreply.github.com> Date: Fri, 2 Oct 2020 15:35:26 +0530 Subject: [PATCH] Create fibonacciBottomUp.cpp --- fibonacciBottomUp.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 fibonacciBottomUp.cpp diff --git a/fibonacciBottomUp.cpp b/fibonacciBottomUp.cpp new file mode 100644 index 0000000..fa7c728 --- /dev/null +++ b/fibonacciBottomUp.cpp @@ -0,0 +1,55 @@ +//In the bottom-up dynamic programming approach, we’ll reorganize the order in which we solve the subproblems +//This will allow us to use less memory space in our code. +#include +using namespace std; + +//space O(n) +int fib(int n,int dp[]){ + for(int i=2;i<=n;i++){ + dp[i]=dp[i-1]+dp[i-2]; + } + return dp[n]; +} + +//space O(1) +int fib_Space_Opt(int n){ + //base case + if(n == 0 || n == 1) return n; + + int a = 0; + int b = 1; + int c; + + for(int i=2;i<=n;i++){ + c = a + b; + a = b; + b = c; + } + return c; +} + + +int main() { + int n; + cout<<"Enter number 'n' to find nth fibonacci number: "; + cin>>n; + int dp[n+1]={0}; + dp[1] = 1; + + cout<<"Output calculated with space complexity O(n): "; + cout<