add a DP solution O(mn)