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
相关推荐
CoovallyAIHub14 分钟前
CVPR 2026 | GS-CLIP:3D几何先验+双流视觉融合,零样本工业缺陷检测新SOTA,四大3D工业数据集全面领先!
深度学习·算法·计算机视觉
xlp666hub35 分钟前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
有意义3 小时前
深度拆解分割等和子集:一维DP数组与倒序遍历的本质
前端·算法·面试
xlp666hub4 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
用户726876103374 小时前
解放双手的健身助手:基于 Rokid AR 眼镜的运动计时应用
算法
Wect4 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·typescript
明月_清风6 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风6 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
xlp666hub21 小时前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法