class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
# 判断当前字段是否合法
def judge_ip_segment(s,left,right):
# 当前ip段的大小
size = right-left + 1
# 长度大于1的情况下,当前段ip起始不能为0
if size > 1 and s[left]=='0':
return -1
# 转为int
res = int(s[left:right+1])
# 不能超过255
if res > 255:
return -1
return res
# 递归调用
# begin是从s中的哪一位开始
# split_times看是已经完成多少段了,正常4段
# size记录数组的长度
def dfs(s,begin,size,split_times,path,res):
if begin == size:
# 遍历完成
if split_times == 4:
res.append(".".join(path))
return
if size - begin < (4-split_times) or size -begin > 3 * (4-split_times):
# 当前字符串长度最小为4,最大为3*4,因为没段最少一位,最多三位,不满足直接返回
return
# 每段最多三种分支,位数为1、位数为2、位数为3
for i in range(3):
# 不能超过字符串长度
if begin + i >= size:
return
ip_segment = judge_ip_segment(s,begin,begin+i)
# 只要当前段ip合法
if ip_segment != -1:
path.append(str(ip_segment))
# 继续遍历下一个
dfs(s,begin+i+1,size,split_times+1,path,res)
path.pop()
size = len(s)
if size < 4 or size > 12:
return []
path = []
res = []
dfs(s,0,size,0,path,res)
return res
每日一道Leetcode - 93. 复原 IP 地址 【回溯】
最新推荐文章于 2024-06-20 17:54:56 发布