0

I am currently trying to solve a task with memoization. I have following recursion:

A (i, j) = f( A (i, j-1), A (i-1, j-1), A (i-1, j + 1) )

I am not sure in which order the sub-problems should be solved best, so that multiple calculations are avoided.

Does someone have an idea which order is best?

1 Answers1

2

Let me show you the general approach to figuring this out. Then I'll let you apply that technique to your specific situation.

Well, it's clear that you need to solve $A(i,j-1)$, $A(i-1,j-1)$, and $A(i-1,j+1)$ before solving $A(i,j)$. So, you need to pick an order that ensures all three of those are solved before you try to solve $A(i,j)$. What order would work for that?

I suggest you try drawing a picture. Draw a grid, with one dot for each $(i,j)$. Draw an arrow from $(i,j-1)$ to $(i,j)$, an arrow from $(i-1,j-1)$ to $(i,j)$ and an arrow from $(i-1,j+1)$ to $(i,j)$ for each $(i,j)$. You might do this for, say, a 4x4 grid. Look at the resulting picture. Can you find an order of traversing the dots, so that is consistent with all of the arrows? Hint: try topological sorting that graph. What order does that give you? Can you generalize? What would work for a 5x5 grid?

If you're not sure, just write a recursive program and apply memoization. Then you won't need to explicitly pick an order to build things out bottom-up; the computer will take care of that for you. See When can I use dynamic programming to reduce the time complexity of my recursive algorithm? and https://en.wikipedia.org/wiki/Memoization.

D.W.
  • 167,959
  • 22
  • 232
  • 500