93. 复原 IP 地址 是回溯中分割问题的一道比较典型的题目。
同理之前的题目,路径path
收集每一个结果,最后res
作为结果集输出。
判断是否是ip地址使用函数isIp
来判断,看他是否在0-255
之间;同时不要忘记IP地址除0之外不能以0开头。这两个判断条件可以在最后path
形成后使用all()
来检测;也可以在过程中就把他排除掉。
形成path
之后用join
来变成ip地址加进res
。
终止条件:
循环的终止条件是path
中已经有4个ip;这时候如果s
剩余为空表明已经分割完成了。如果每一个ip符合条件,就可以把他们加进结果集合里面。
循环内部条件与回溯模版一致,每一次截取s
头部的一串字符串s[:index + 1]
,然后把余下的部分递归。
整体代码如下:
class Solution:
def isIp(self, num):
return False if num < 0 or num > 255 else True
def partition(self, s, path, res):
if len(path) == 4:
# if not s and all(self.isIp(int(num)) for num in path):
if not s:
res.append('.'.join(path))
return
return
for index in range(len(s)):
if s[: index + 1] != '0' and s[:index + 1][0] == '0':
continue
if not self.isIp(int(s[:index + 1])): continue
path.append(s[:index + 1])
self.partition(s[index + 1:], path, res)
path.pop()
return
def restoreIpAddresses(self, s: str):
if len(s) > 12 or len(s) < 4: return []
path = []
res = []
self.partition(s, path, res)
return res