思路简单,状态转移方程容易想。需要注意的是转移时的一些状态,比如是否连通,等等。
class Solution: def maxVacationDays(self, flights: List[List[int]], days: List[List[int]]) -> int: n = len(flights) k = len(days[0]) adjLists = {} for i in range(n): for j in range(n): if flights[i][j] == 1 or i == j: # i --> j if j not in adjLists: adjLists[j] = [] adjLists[j].append(i) memo = {} # i, j : i - city; j - week; max days for vacation result = 0 for j in range(k): for i in range(n): if j == 0: # first week if 0 in adjLists[i]: memo[(i, j)] = days[i][j] else: memo[(i, j)] = -1 else: # j > 0 maxTmp = -1 for city in adjLists[i]: maxTmp = max(memo[(city, j - 1)], maxTmp) if maxTmp != -1: memo[(i, j)] = maxTmp + days[i][j] else: memo[(i, j)] = -1 result = max(result, memo[(i, j)]) return result