Holy crap, memoization was absolutely clutch for this one.