Zookeeper
Recursion & Dynamic Programming
Recursion:
Recursion solution, by definition, are built off solutions to sub problems. usually times, this will mean simply to compute f (n) by adding something, removing something, or otherwise changing the solution for (n-1 ). in other cases, you might have to do something more complicated.
You shoshould 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 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 maid (int n)
{
If (I <0) return-1;
If (I = 0) return 0;
If (I = 1) return 1;
Return maid (n-1) + maid (n-2 );
}
·Solution 2: Dynamic programming (recursive + cache)
Publicint maid (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 maid (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];
}