October 22, 2007
C++ Hash Table Memoization: Simplifying Dynamic ProgrammingDP Problems
From my perspective, the traditional approach to DP suffers from a couple of problems.
First, it seems to me that people feel more comfortable attacking problems in a top-down fashion as opposed to bottoms-up. This is certainly a matter of psychology, not computer science, but it is relevant to consider human factors when designing for maintenance, testability, and review. In many cases the expression of the algorithm seems more natural when given in the original top-down mode, and requires fewer mental gymnastics on the part of whoever is studying the algorithm.
The second problem is the traditional use of array structures to hold subproblems. The problem starts to creep into play when you look at algorithms like Matrix Chain Multiplication, in which half of the storage space is not even used. Things get even worse when you use a problem like that described later in this article, in which subproblems just don't fit into a row/column organizational format.
Both of these problems can be addressed effectively by using standard C++ hash tables. The procedure is as follows:
With these minor changes, which can often be accomplished in change to as few as three lines of code, you can convert your inefficient recursive algorithm to use dynamic programming, without having to refactor to a bottoms-up implementation, and without having to shoehorn your results into tabular format.
A Simple Example
Applying this technique to our Fibonacci example, we get a routine that looks like this:
std::map<int,int> results;
int fib( int n )
{
if ( n == 0 || n == 1 )
return 1;
std::hash_map<int,int>::iterator ii = results.find( n );
if ( ii != results.end() )
return ii.second;
else
return results[ n ] = fib( n -1 ) + fib( n - 2 );
}
So the first time we encounter fib(4), we have to make the recursive calls to fib(3) and fib(2). But the second time around, the result has been stored in the map, and it is returned without any additional calculations taking place.
|
|
||||||||||||||||||||||||||||||
|
|
|
|