Pinterest interview question

Hard backtracking question from leetcode