Pattern matching - dynamic programming