Recursion & Dynamic Programming



Recursion & Dynamic Programming


Recursion:

Recursion solution, by definition, are built off solutions to sub problems. Many times, this will mean simply to compute f(n) by adding something, removing something, or otherwise changing the solution for for(n-1). In other cases, you might have to do something more complicated.

You should consider both bottom-up and top-down recursive solutions. The Base Case and Build approach works quite well for recursive problem.

·         Bottom-Up recursion

Bottom-up recursion is often the most intuitive. We start with knowing how to solve the problem for a simple case, like a list with only one element, and figure out how to solve the problem for two elements, then for three elements, and so on. The key here is to think about how you can build the solution for one case off of the previous case.

·         Top-Down Recursion

Top-Down Recursive can be more complex, but it is sometimes necessary for problems. In these problems, we think about how we can divide the problem for case N into sub-problems. Be careful of overlap between the cases.

 

Dynamic Programming.

Almost problems of recursion can be solved by dynamic programming approach.  A good way to approach such a problem is often to implement it as a normal recursive solution, and then to add to add the caching part.

 

Example:  compute Fibonacci Numbers (C#)

f(0)

f(1)

f(2)

f(3)

f(4)

f(5)

....

f(n-1)

f(n)

0

1

1

2

3

5

.....

f(n-3)+f(n-2)

f(n-1)+f(n-2)

 

·         solution 1: Recursive

public int Fibonacci(int n)

{

   if(i<0)  return -1;

   if(i==0) return 0;

   if(i==1) return 1;

   return Fibonacci(n-1)+ Fibonacci(n-2);

}

 

·         Solution 2: Dynamic programming (recursive + cache)

public int Fibonacci(int n)

{

    if(n<0) {throw new Exception("Invalid Inputs!");}

 

    int[] R=new int[n+1]; // by default, let us say the index is started from 0

    R[0]=0;

    R[1]=1;

    for(int i=2; i<=n; i++)

     {

          R[i]=-1;

     }

 

    return FindFromArrayR(n, R);

}

private int FindFromArrayR(n,R)

{

   if(R[n] !=-1) {return R[n];}

 

   else { R[n]= FindFromArrayR(n-1, R) + FindFromArrayR(n-2, R);}

 

   return R[n];

}

 

·         solution 3: Iterative  

public int Fibnacci(int n)

{

   if(n<0) { throw new Exception("Invalid Inputs");}

   int[] R=new int[n+1];

   R[0]=0;

   R[1]=1;

   for(int i=2; i<=n; i++)

    {

       R[i]=R[i-1]+R[i-2];

    }

    return R[n];

}

   


你可能感兴趣的:(Recursion & Dynamic Programming)