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
相关推荐
Monodye5 分钟前
【Java】网络编程:TCP_IP协议详解(IP协议数据报文及如何解决IPv4不够的状况)
java·网络·数据结构·算法·系统架构
pzx_00110 分钟前
【内积】内积计算公式及物理意义
数据结构·python·opencv·算法·线性回归
一丝晨光11 分钟前
逻辑运算符
java·c++·python·kotlin·c#·c·逻辑运算符
元气代码鼠12 分钟前
C语言程序设计(进阶)
c语言·开发语言·算法
ForRunner12314 分钟前
使用 Python 高分解决 reCAPTCHA v3 的指南
数据库·python·microsoft
十雾九晴丶1 小时前
攻防世界--->gametime
算法
躺平的花卷1 小时前
Python爬虫案例六:抓取某个地区某月份天气数据并保存到mysql数据库中
数据库·爬虫·python·mysql
虚拟搬运工1 小时前
Python类及元类的创建流程
开发语言·chrome·python
Aurora_th2 小时前
树与图的深度优先遍历(dfs的图论中的应用)
c++·算法·深度优先·图论·dfs·树的直径
学步_技术2 小时前
Python编码系列—Python原型模式:深克隆与高效复制的艺术
开发语言·python·原型模式