Necessary and Sufficient Conditions for Optimal Decision Trees using Dynamic Programming