Recursion & Dynamic Programming

来源:互联网 发布:ubuntu dd iso 编辑:程序博客网 时间:2024/06/11 00:57


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

publicint 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)

publicint Fibonacci(int n)

{

   if(n<0) {thrownewException("Invalid Inputs!");}

 

   int[] R=newint[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);

}

privateint 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  

publicint Fibnacci(int n)

{

  if(n<0) {thrownewException("Invalid Inputs");}

  int[] R=newint[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];

}

   


0 0