classSolution(object): defnumberOfArrays(self, differences, lower, upper): """ :type differences: List[int] :type lower: int :type upper: int :rtype: int """
""" # 看了一个示例后,感觉只算一遍,然后算一个max low就可以了吧 result = 0 for start_idx in range(lower, upper+1): tmp_start_idx = start_idx flag = True for i in range(len(differences)): tmp_start_idx += differences[i] if not (tmp_start_idx <= upper and tmp_start_idx >= lower): flag = False break if flag: result += 1 return result """ result = 0 tmp_start_idx = lower seq_max = lower seq_min = lower for i inrange(len(differences)): tmp_start_idx += differences[i] seq_max = max(seq_max, tmp_start_idx) seq_min = min(seq_min, tmp_start_idx) # print("seq_max: ", seq_max) # print("seq_min: ", seq_min)
# 把四个方向满足条件的加入到队列中 for i inrange(4): nx = now_x + dx[i] ny = now_y + dy[i] if nx >= 0and nx < m and ny >= 0and ny < n and grid[nx][ny] != 0and vis[nx][ny] == 0: vis[nx][ny] = 1 bfs_queue.append([nx, ny, now_step+1, grid[nx][ny]])
# dfs(x, y, 0) result.sort(key=lambda x: (x[2], x[3], x[0], x[1])) iflen(result) > k: return [[result[x][0], result[x][1]] for x inrange(k)] else: return [[x[0], x[1]] for x in result]
# 一眼看过去很像dfs啊,d就完事了,会不会超时之后再说了 m = len(grid) n = len(grid[0]) vis = [[0for _ inrange(n)] for _ inrange(m)] dx = [0, 1, 0, -1] dy = [1, 0, -1, 0]
x = start[0] y = start[1] vis[x][y] = 1
result = [] mappings = {}
defdfs(x, y, step): if grid[x][y] <= pricing[1] and grid[x][y] >= pricing[0]: if mappings.get((x, y)) isNone: mappings[(x, y)] = [step, grid[x][y]] else: tmp_list = mappings[(x, y)] if step < tmp_list[0]: mappings[(x, y)] = [step, grid[x][y]]
for i inrange(4): nx = x + dx[i] ny = y + dy[i] if nx >= 0and nx < m and ny >=0and ny < n and grid[nx][ny] != 0and vis[nx][ny] == 0: vis[nx][ny] = 1 dfs(nx, ny, step+1) vis[nx][ny] = 0
dfs(x, y, 0)
for key, value in mappings.items(): result.append([key[0], key[1], value[0], value[1]])