Used a hash table for memorization; now much faster