0

I came across the following problem:

F(n)= 0 when n = 0;
F(n)= 1 when n = 1;
F(n)= F(n-1) + F(n-2) when n>1;

I can already solve this recursively like this:

int F(int n) {
    if(n=0) return 0;
    if(n=1) return 1;
    if(n>1) return F(n-1) + F(n-2);
}

but the complexity is O(n^2). How can this be solved with the complexity O(n)?

What book should I need to read to solve a problem like this?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
judy T
  • 11
  • 2

1 Answers1

1

This function is exactly what you are looking for. And yes, this is Dynamic Programming.

static ArrayList<Double> getSeries(int n)
{
    ArrayList<Double> series = new ArrayList<>();
    series.add(0.0); // This is working as replacement of the F(0)
    series.add(1.0); // This is working as replacement of the F(1)
    double x, y;

    for (int i = 1; i < n; i++)
    {
        x= series.get(i - 1); // This is working as replacement of the F(n-2)
        y = series.get(i); // This is working as replacement of the F(n-1)
        series.add(x + y);
    }

    return series;
}

Try this code here:- https://ideone.com/IMixm9

The basic trade-off of computational space and time can be seen here.

Before

Space Complexity :- log 
Time Complexity  :- 2^n

Now

Space Complexity :- n
Time Complexity  :- n
Ashish Sharma
  • 31
  • 1
  • 3