Leetcode93.复原IP地址 - Restore IP Addresses - Python - 回溯法

解题思路:

1.此题与Leetcode131.分割回文串十分相似。

请参考:Leetcode131.分割回文串-Palindrome Patitioning-Python-回溯法-CSDN博客

2.在此基础上,需要添加逗点,以及当前进入递归函数的字符串是否合法。

代码:

class Solution(object):
    result = []
    path = []
    def trackBacking(self, s, startIndex, pointNum):
        if startIndex == len(s) and pointNum == 4:
            self.result.append('.'.join(self.path))
            return
        for i in range(startIndex, len(s)):
            if self.isValid(s, startIndex, i):
                self.path.append(s[startIndex: i+1])
                pointNum += 1
                self.trackBacking(s, i+1, pointNum)
                self.path.pop()
                pointNum -= 1
    
    def isValid(self, s, start, end):
        if start>end:
            return False
        if s[start] == '0' and start != end:
            return False
        num = 0
        for i in range(start, end+1):
            if not s[i].isdigit():
                return False
            num = num * 10 + int(s[i])
        if num > 255:
            return False
        return True

    def restoreIpAddresses(self, s):
        self.result = []
        self.trackBacking(s, 0, 0)
        return self.result

你可能感兴趣的:(算法,leetcode,python)