class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
path = []
res = []
def isip(ch):
if int(ch) > 255:
return False
if len(ch) > 1 and ch[0] == '0':
return False
return True
def backtrack(idx):
if idx == len(s) and len(path) == 4:
#这里直接在path中每个数字后面加了一个点
res.append('.'.join(path))
return
#如果上一层path已经是4,但不满足条件,这层递归可以直接停止
if len(path) > 4:
return
#这里剪枝,我们只需遍历到 带上idx 后三位即可
for i in range(idx,min(idx+3,len(s))):
if isip(s[idx:i+1]):
path.append(s[idx:i+1])
# print(path)
backtrack(i+1)
path.pop()
backtrack(0)
return res
93. 复原 IP 地址
最新推荐文章于 2024-07-18 15:53:23 发布