AC solution

O(N^4) DP solution or partially Floyd Marshall with recursive path tracking.