P301: Optimized all solutions with more math and dynamic programming.