Dynamic Programming: Recursive, Memoized, Top-Down Solutions

    Dynamic Programming: Recursive, Memoized, Top-Down Solutions

      Top-down solutions start with one big problem and work down to the little problems that help solve that one big problem. It's like when you accidentally flush your family's beloved pet salamander down the toilet.

      How did you manage to flush it down the toilet? Who knows. The point is that you did it, and now you need to solve the problem of keeping everyone from noticing that Salamander Rushdie is gone before finding his replacement.

      To sum, the big problem is getting a new salamander. Before you can solve the big problem, though, you need to solve sub-problems like

      • keeping people from checking Rushdie's cage.
      • finding a salamander that looks like Sal. 
      • getting the new salamander into the house without anyone noticing. 
      • keeping the new salamander from bathing in the toilet like its unfortunate namesake.

      As much as we love brainstorming plots for cheesy sitcoms, let's move away from toilet-surfing salamanders. Instead, let's talk a little more about Fibonacci and how to structure a top-down approach using memoization and recursion.

      Both. At the same time. Can you imagine?

      Declare an array to store Fibonacci numbers
      INITIALIZE each spot in the array to a non-meaningful value
      INITIALIZE the 0th and 1st elements of array to account for base cases
       
      Define the FIBONACCI function
      	IF the nth element of the array is greater than or equal to zero THEN
      		Return nth element
      	ELSE 
      		SET nth element of array to FIBONACCI of n – 1 plus FIBONACCI of n – 2
      		Return nth element
      	END IF

      We started with n, at the top of the tree, and worked downward from there, hence that whole "top-down" bit. This solution also gives the recursive efficiency and cuts out unnecessary recalculations by using an array to store intermediate results.

      Problem, consider yourself dynamically programmed.