class Solution:
"""
step1, set limit for 4 level recursion and stop; check if all string are used, if yes, push into result. otherwise ignore. return current path
step2, set substring length limit: 1-3. and discuss number restrictions based on length variety. (len== 1: no restriction; len ==2: first number not '0'; len == 3 first num not '1' and total number <=255)
step3, when current substring meets desired standard, make the rest string go to next recursion.
"""
def restoreIpAddresses(self, s: str) -> List[str]:
res = []
def dfs(ss,level,path,res):
if level == 4:
if not ss:
# print(path[-1])
res.append(path[:-1])# remove last '.'
return #!!! be careful the position not algined with res
# @i: length of substring at each segment
# substring length max is 3
for i in range(1,4):
if i <= len(ss): #!!!! important, make sure i is not overflow
#sub = s[:i]
if i == 1:
dfs(ss[i:],level+1,path+ss[:i]+'.',res)
elif i == 2 and ss[0]!='0':
dfs(ss[i:],level+1,path+ss[:i]+'.',res)
elif i == 3 and ss[0]!='0' and int(ss[:3]) <= 255:
dfs(ss[i:],level+1,path+ss[:i]+'.',res)
dfs(s,0,"",res)
return res