Skip to content

Ignoring Space wastage in Top Down #36

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

Closed
wants to merge 1 commit into from
Closed
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
20 changes: 14 additions & 6 deletions dynamic_programming_problems/fibonacci.cpp
Original file line number Diff line number Diff line change
@@ -8,22 +8,25 @@
//bottom up

int fib1(int n) {
std::vector<int> fib(n, 0);
// space optimization
std::vector<int> fib(3, 0);
if ( n == 0 || n == 1 ) {
return 1;
}
fib[0] = 1;
fib[1] = 1;
for ( int i = 2; i < n; ++i ) {
fib[i] = fib[i-1] + fib[i-2];
fib[2] = fib[1] + fib[0];
fib[0] = fib[1];
fib[1] = fib[2];
}
return fib[n-1];
return fib[1];
}

//top down

std::vector<int> fib(1000, 0);
int fib2( int n ) {
// Ignoring Space wastage
int fib2( int n , int * fib) {
if ( n == 0 ) {
return 0;
}
@@ -38,6 +41,7 @@ int fib2( int n ) {
}

//leverage the fact we are just using last 2 term
// bottom up
int fib3( int n ) {
int a = 0;
int b = 1;
@@ -52,7 +56,11 @@ int fib3( int n ) {

int main()
{
int n;
std::cout << "\Enter n\t:\t";
std::cin >> n;
int * fib = new int[n];
std::cout << "Demonstrating fibonacci term calculation:\n";
std::cout << fib1(9) << " " << fib2(9) << " " << fib3(9) << std::endl;
std::cout << fib1(b) << " " << fib2(n , fib) << " " << fib3(n) << std::endl;
return 0;
}