使用回溯时,如何可靠地跟踪答案?

问题描述

我一直在尝试使用回溯法来解决this problem,但是在跟踪找到的答案时遇到了问题。

我的代码

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:
            #print(self.ans)
            self.ans.append(path)
            #print(self.ans)
            return

        if s == "" or len(path) >= 4:
            return

        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])
            self.backtrack(path,s[i:])
            path.pop()

a = Solution()
print(a.restore_ip("25525511135"))

当我尝试运行此代码时,它输出以下内容[[],[]]; 但是我期望这样:[['255','255','11','135'],['255','111','35']]; 当我取消注释代码中的两个print()时,其输出如下:

[['255','135']]
[['255','35'],'35']]
[[],[]]

由此我推断出我的总体逻辑是正确的,但是存储在ans类的Solution变量中的答案却以某种方式弄乱了。

有人可以帮助我解决这个问题吗?

谢谢,祝你有美好的一天!

解决方法

python通过引用传递参数,因此您附加到pathans的{​​{1}}是对象

您需要复制指定给回溯的路径对象(在py3中为path.pop(),在py2中为path.copy()):

path[:]
,

您应该通过返回值来跟踪解决方案的状态。

找到解决方案后,您将返回True并停止回溯。

P.S。

您可以将方法转换为静态方法,因为答案与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"))