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];

}

   


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值