Microsoft Interview Question

HackerRank Medium question. Solved it with backtracking and memoization.