classSolution: defbicycleYard(self, position: List[int], terrain: List[List[int]], obstacle: List[List[int]]) -> List[List[int]]: n = len(terrain) m = len(terrain[0]) minSpeed = [[float('inf')] * m for _ inrange(n)] direction = ((1, 0), (0, 1), (0, -1), (-1, 0)) seen = set() defdfs(i, j, speed): if speed <= 0: return if (i, j, speed) in seen: return seen.add((i, j, speed)) minSpeed[i][j] = min(minSpeed[i][j], speed) for di, dj in direction: ni = i + di nj = j + dj if ni < n and ni >= 0and nj >= 0and nj < m: newSpeed = speed + terrain[i][j] - terrain[ni][nj] - obstacle[ni][nj] if (ni, nj, newSpeed) notin seen: dfs(ni, nj, newSpeed) dfs(position[0], position[1], 1) minSpeed[position[0]][position[1]] = float('inf') ans = [] for i inrange(n): for j inrange(m): if minSpeed[i][j] == 1: ans.append([i, j]) return ans
时间复杂度: O(m * n * maxTerrain),
空间复杂度: O(m * n * maxTerrain).
classSolution: defvolunteerDeployment(self, finalCnt: List[int], totalNum: int, edges: List[List[int]], plans: List[List[int]]) -> List[int]: neighbour = collections.defaultdict(list) for a,b in edges: neighbour[a].append(b) neighbour[b].append(a) coef = [[1,0]] for c in finalCnt: coef.append([0,c]) for i inrange(len(plans)-1, -1, -1): num, idx = plans[i] if num == 1: coef[idx] = [coef[idx][0]*2, coef[idx][1]*2] elif num == 2: for nei in neighbour[idx]: coef[nei] = [coef[nei][0]-coef[idx][0], coef[nei][1]-coef[idx][1]] else: for nei in neighbour[idx]: coef[nei] = [coef[nei][0]+coef[idx][0], coef[nei][1]+coef[idx][1]] divide = 0 for a,b in coef: totalNum -= b divide += a x = totalNum//divide ans = [] for a,b in coef: ans.append(a*x+b) return ans
时间复杂度: O(m * n * avg(edges)),
空间复杂度: O(edges + n).
classSolution: defsecurityCheck(self, capacities: List[int], k: int) -> int: MOD = 1000000007 n = len(capacities) @cache defdp(i, k): # the current first capcities index, k is the number we want to pop first # print(i,k) if i == n - 1: ans = 0 if k == 0: # queue ans += 1 if k == capacities[n-1] - 1: ans += 1 return ans else: ans = 0 c = capacities[i] if k >= c - 1: ans += dp(i+1, k - (c - 1)) # stack ans += dp(i+1, k) # queue return (ans) % MOD ans = dp(0, k) dp.cache_clear() return ans