Well, stochastic memoization seems to work.