Continual Learning via Dynamic Programming