切割问题就可以使用回溯搜索法把所有可能性搜出来
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
result = []
def isValid(s, start, end):
if start > end: return False
if s[start] == '0' and start != end:
return False
if not 0 <= int(s[start:end+1]) <= 255:
return False
return True
def backtracking(s, startIndex, pointNum):
if pointNum == 3:
if isValid(s, startIndex, len(s)-1):
result.append(s[:])
return
for i in range(startIndex, len(s)):
if isValid(s, startIndex, i):
s = s[:i+1] + '.' + s[i+1:]
backtracking(s, i+2, pointNum+1)
s = s[:i+1] + s[i+2:]
else:
break
if len(s) > 12: return []
backtracking(s, 0, 0)
return result