python - 这两种方法在 Python 中如何具有不同的时间复杂度?
问题描述
我正在尝试解决Leetcode 单词搜索问题。
我有两个解决方案对我来说是相同的,尽管其中一个在 Time Limit Exceeded 中返回。
我阅读了有关此的所有资源,但无法理解幕后发生的事情。
具有优化时间复杂度的解决方案 1:
class Solution(object):
def bfs(self, position, visited, board, word):
# print(position)
if not word:
return True
destination = [(-1,0), (1,0), (0,1), (0,-1)]
res = False
for x,y in destination:
new_postion_x, new_postion_y = position[0] + x, position[1] + y
if (0<= new_postion_x < len(board)) and (0 <= new_postion_y < len(board[0])) and (new_postion_x, new_postion_y) not in visited:
if board[new_postion_x][new_postion_y] == word[0]:
new_visited = visited.copy()
new_visited[(new_postion_x,new_postion_y)] = 1
res = res or self.bfs((new_postion_x, new_postion_y), new_visited, board, word[1:])
return res
def exist(self, board, word):
for i in xrange(len(board)):
for j in xrange(len(board[0])):
if board[i][j] == word[0]:
t = self.bfs((i,j), {(i,j): 1}, board, word[1:])
if t:
return True
return False
解决方案二在执行大输入时返回 TLE:
class Solution(object):
def bfs(self, position, visited, board, word):
print(position)
if not word:
return True
destination = [(-1,0), (1,0), (0,1), (0,-1)]
res = False
for x,y in destination:
new_postion_x, new_postion_y = position[0] + x, position[1] + y
if (0<= new_postion_x < len(board)) and (0 <= new_postion_y < len(board[0])) and (new_postion_x, new_postion_y) not in visited:
if board[new_postion_x][new_postion_y] == word[0]:
new_visited = visited.copy()
new_visited[(new_postion_x,new_postion_y)] = 1
t = self.bfs((new_postion_x, new_postion_y), new_visited, board, word[1:])
res = res or t
return res
def exist(self, board, word):
for i in xrange(len(board)):
for j in xrange(len(board[0])):
if board[i][j] == word[0]:
t = self.bfs((i,j), {(i,j): 1}, board, word[1:])
if t:
return True
return False
解决方案
关键线在这里:
res = res or self.bfs((new_postion_x, new_postion_y), new_visited, board, word[1:])
一旦res
变为True
,此行将永远不会再次执行,因为不需要计算self.bfs()
之后的表达式。or
这称为短路。
因此,一旦找到解决方案,您就不会再进行任何递归调用并快速将True
所有方法返回到顶部。写这个的一种等效方式,可能会澄清它,将是:
if not res:
res = self.bfs(...)
在另一个解决方案中:
t = self.bfs((new_postion_x, new_postion_y), new_visited, board, word[1:])
res = res or t
即使不再需要它,它也会始终调用,即使已经找到解决方案,它也会始终搜索整个图形。self.bfs()
推荐阅读
- html - 将鼠标悬停在未占据标题全部高度的列表项上
- javascript - 提交表单并插入数据库时如何解决问题?
- delphi - Delphi FireDAC TFDQuery 参数 - SQL Server Native Client 11.0 - 数值超出范围
- android - 如果我想在滑动后调用操作,如何在 Compose 中实现滑动
- json - Jmeter 中的 GraphQL - 变量和参数
- python - 将列表中的数据转换为新矩阵中的分隔行和列
- vue.js - 摄影主题 - 标准许可证 x 1
- android - 我想在我的服务中使用 UsageStatsManager
- javascript - Javascript中READONLY选择列表中的Apex更改值
- linux - genhtml:错误:仅在 Linux 上无法读取文件路径