DP and dfs solution