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
相关推荐
乐迪信息4 小时前
智慧港口船舶AI算法实现在线状态监测
大数据·人工智能·深度学习·算法·计算机视觉
2601_962381585 小时前
【转】Python渗透测试工具:sqlmap
python·渗透测试·sql注入·sqlmap·数据库安全
用户3721574261355 小时前
如何使用 Python 从 Word 文档中提取图片
python
木井巳6 小时前
【BFS/DFS 解决 FloodFill 算法】太平洋大西洋水流问题
java·算法·leetcode·深度优先·广度优先·宽度优先·推荐算法
心抵鹊7 小时前
归并排序之翻转对(hard)
数据结构·算法
白山编程大哥7 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
shehuiyuelaiyuehao7 小时前
算法34,位运算符操作,总结
算法
Navigator_Z7 小时前
LeetCode //C - 1224. Maximum Equal Frequency
c语言·算法·leetcode
Navigator_Z8 小时前
LeetCode //C++ - 1226. The Dining Philosophers
c语言·算法·leetcode
昭昭日月明8 小时前
RAGFlow 入门,不用从零造轮子
python·ai编程