2 回答

TA貢獻1799條經驗 獲得超8個贊
python 通過引用傳遞參數,以便path
您附加到ans
和path.pop()
是對象
您需要復制給回溯的路徑對象(path.copy()
在 py3 中,path[:]
在 py2 中):
self.backtrack(path.copy(), s[i:]) ^^^^^^^^^^^

TA貢獻1111條經驗 獲得超0個贊
您應該通過返回值來跟蹤解決方案的狀態。
當找到解決方案時,您返回True并停止回溯。
聚苯乙烯
您可以將該方法轉換為靜態方法,因為答案與對象狀態無關Solution,從而能夠使用不同線程解決多個問題。
class Solution:
def restore_ip(self, s):
self.ans = []
self.backtrack([], s)
return self.ans
def backtrack(self, path, s):
if s == "" and len(path) == 4:
self.ans = path
return True
if s == "" or len(path) >= 4:
return False
for i in range(1, len(s)+1):
if i > 3:
break
if int(s[:i]) > 255:
break
if i != 1 and s[0] == 0:
break
path.append(s[:i])
if self.backtrack(path, s[i:]):
return True
path.pop()
a = Solution()
# ['255', '255', '11', '135']
print(a.restore_ip("25525511135"))
添加回答
舉報