Completed naive recursive algorithm

- write it as dynamic programming