Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get fibonacci using memoization and dynamic programming #135

Merged
merged 1 commit into from
Oct 27, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions fibonacci.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#include <iostream>
using namespace std;

int fibonacci(int num)
{
if (num <= 1)
{
return num;
}
int a = fibonacci(num - 1);
int b = fibonacci(num - 2);
return a + b;
}

int fibonacci_mem_helper(int n, int *ans)
{
if (n <= 1)
{
return n;
}
if (ans[n] != -1)
{
return ans[n];
}
int a = fibonacci_mem_helper(n - 1, ans);
int b = fibonacci_mem_helper(n - 2, ans);
ans[n] = a + b;
return ans[n];
}

int fibonacci_mem(int n)
{
int *ans = new int[n + 1];
for (int i = 0; i <= n; i++)
{
ans[i] = -1;
}
return fibonacci_mem_helper(n, ans);
}

int fibo_3(int n)
{
int *ans = new int[n + 1];
ans[0] = 0;
ans[1] = 1;
for (int i = 2; i <= n; i++)
{
ans[i] = ans[i - 1] + ans[i - 2];
}
return ans[n];
}
int main()
{
cout << fibonacci_mem(6);
}