Microsoft interview question

HackerRank Medium question. Solved it with backtracking and memoization.