Leetcode_med 93. 复原IP地址

本文介绍了一种通过回溯算法解决复原IP地址问题的方法。针对一个由数字组成的字符串,算法可以找出所有可能的IP地址格式组合。具体实现包括限制每个部分的数字长度不超过3位,并确保数值范围在0到255之间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。

示例:

输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]

Python

笨方法

class Solution:
    def restoreIpAddresses(self, s):
        ret = []
        for a in range(1, 4):
            for b in range(1, 4):
                for c in range(1, 4):
                    d = len(s) - a - b - c
                    """
                      Last number must use all remaining digits. Check;
                      1. The size of the last number is valid
                      2. Every number uses 1 digit for 0 and is less than 255 if using 3 digits
                    """
                    if (1 <= d <= 3 and
                    (1 == a or '0' != s[0        ]) and (a != 3 or s[         :a        ] <= "255") and
                    (1 == b or '0' != s[a        ]) and (b != 3 or s[a        :a + b    ] <= "255") and
                    (1 == c or '0' != s[a + b    ]) and (c != 3 or s[a + b    :a + b + c] <= "255") and
                    (1 == d or '0' != s[a + b + c]) and (d != 3 or s[a + b + c:         ] <= "255")):
                        ret.append('.'.join([s[0:a], s[a:a + b], s[a + b:a + b + c], s[a + b + c:]]))
        return ret

backtracking(更好的方案)

class Solution:
    def restoreIpAddresses(self, s):
        ret = []
        self.dfs(s,0,'',ret)
        return ret
    
    def dfs(self,s,index,path,ret):
        if index == 4:# already have 4 items
            if not s: 
                ret.append(path[:-1]) # leave the last '.'
            return # attention backtracking needs return when is working or not
    
        for i in range(1,4):# 3 is the max length
            if i <=len(s):
                if i==1 :
                    self.dfs(s[i:],index+1,path+s[:i]+'.',ret)
                if i==2 and s[0] != '0':
                    self.dfs(s[i:],index+1,path+s[:i]+'.',ret)
                if i==3 and s[0] != '0' and int(s[:i])<=255:
                    self.dfs(s[i:],index+1,path+s[:i]+'.',ret)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值