这个题还是普通型回溯算法,问题就是在解决先导0的写法上,我直接用的step对应的上限和下限,举个例子:
如果step==0,说明只读一个单位长度的字符,所以范围在0~9(其实就是没限制);
但是如果step==1,说明读入两个单位长度字符,转成的数字最小是10就可以解决先导0;
同样step==2,读入三个字符,转数字最小是100解决先导0,但是最大是255
class Solution(object):
def restoreIpAddresses(self, s):
ans=[]
temp=[]
dict_ip={ #这个字典用来解决先导0和上限,其实只有step==2时存在上限255
0:[0,9],
1:[10,99],
2:[100,255]
}
len_s=len(s)
def DFS(i,deepth):
if deepth==4:
if i==len_s:
ans.append('.'.join(temp[:]))
else:
for step in range(3):
if i+step<len_s :
temp_int= int(s[i:i + step + 1])
if temp_int>=dict_ip[step][0] and temp_int<=dict_ip[step][1]:#解决先导0和上限255
temp.append(s[i:i+step+1])
DFS(i+step+1,deepth+1)
temp.pop(-1)
DFS(0,0)
return ans