我正在解决leetcode上的一个问题,并且注意到两个几乎相似的代码在不同的运行时,这两个代码之间的唯一区别是,在其中一个中,我创建了res数组作为Solution类实例变量,而在另一个中,res数组是临时。 下面是区别,慢了将近1.6倍
我尝试了多次,但时差仍然存在吗? 有人可以帮我知道原因吗?
代码1:
class Solution(object):
def __init__(self):
self.res = []
def dfs(self,node,i,j,board,path):
if not node:
return
if node.isComplete:
self.res.append(path)
#since we have already added this word we remove it from our trie.
node.isComplete = False
if i<0 or j<0 or i>=len(board) or j>=len(board[0]):
return
tmp = board[i][j]
nextNode = node.children.get(tmp)
board[i][j]='#'
self.dfs(nextNode,i+1,j,board,path+tmp)
self.dfs(nextNode,i-1,j,board,path+tmp)
self.dfs(nextNode,i,j+1,board,path+tmp)
self.dfs(nextNode,i,j-1,board,path+tmp)
board[i][j]=tmp
def findWords(self, board, words):
trie = Trie()
for w in words:
trie.insert(w)
root = trie.root
for i in xrange(len(board)):
for j in xrange(len(board[0])):
self.dfs(root,i,j,board,"")
return self.res
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
代码2:
class Solution(object):
def findWords(self, board, words):
res = []
trie = Trie()
node = trie.root
for w in words:
trie.insert(w)
for i in xrange(len(board)):
for j in xrange(len(board[0])):
self.dfs(board, node, i, j, "", res)
return res
def dfs(self, board, node, i, j, path, res):
if node.isWord:
res.append(path)
node.isWord = False
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]):
return
tmp = board[i][j]
node = node.children.get(tmp)
if not node:
return
board[i][j] = "#"
self.dfs(board, node, i+1, j, path+tmp, res)
self.dfs(board, node, i-1, j, path+tmp, res)
self.dfs(board, node, i, j-1, path+tmp, res)
self.dfs(board, node, i, j+1, path+tmp, res)
board[i][j] = tmp