下面,是我發布的原始代碼的簡化版本。當代碼運行時,它經過for回圈的第一次迭代,找到一個符合條件的元素(第一個元素)并呼叫函式的另一個實體。注意:在我對遞回的理解中,函式的第一個實體已經 "凍結",一旦函式的第二個實體完成,就等待著迭代到下一個元素,并彈出呼叫堆疊。 然而,當函式的第二個實體完成后,函式的第一個實體并沒有恢復。我在這里錯過了什么?
class Solution。
def main(self,x,y)。
自己。 方向 = [(-1, 0), (0, -1) 。(1, 0), (0,1) ]
self.change={}。
self.func_count = 0] self.func_count = {}.
self.helper(x,y)
def helper(self, x, y)。
self.func_count = 1: self.func_count
print("func count"/span>, self.func_count)
for i, j in self.direction:
print("for loop in func count"/span>, self.func_count)
# 這里是問題所在。一旦一個x i,y j滿足以下條件,就會出現問題。
# 條件,self.helper func就會運行,而不會。
# come back to finish the iteration. Why??
print("x i, y j"/span>, x i, y j)
if x i == 0 and y j == 0:
if (x i,y j) not in self.change:
x = x i
y = y j
self.helper(x,y)
S = 解決方案()
S.main(0,1)
uj5u.com熱心網友回復:
你的代碼總是參考self.func_count,這對所有的遞回呼叫都是一樣的~(也就是說,每個函式呼叫都會遞增和覆寫同一個func_count的副本)。因此,它看起來像該函式從未恢復。
你可以通過定義一個local_func_count來解決這個問題:
self.func_count = 1
local_func_count = self.func_count
和使用它:
print("for loop in func count"/span>, local_func_count)
你的代碼中還有一個潛在的錯誤。self.changed從未被更新。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/312343.html
標籤:
