class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
self.res = []
self.findCombination(s,"",0)
return self.res
def findCombination(self,s,ans,count):
if not s:
return
if count == 3:
curNum = int(s)
if curNum >= 0 and curNum < 256:
ans = ans + "." + s
print ans
self.res.append(ans)
return
length = len(s)
for i in range(1,length+1):
strNum = s[0:i]
curNum = int(strNum)
if curNum >= 0 and curNum < 256:
if count == 0:
oldAns = ans
ans = ans + strNum
self.findCombination(s[i:],ans,count+1)
ans = oldAns
else:
oldAns = ans
ans = ans + "." + strNum
self.findCombination(s[i:],ans,count+1)
ans = oldAns
else:
break
class Solution2(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
self.res = []
self.findCombination(s,"",0)
return self.res
def findCombination(self,s,ans,count):
if not s or len(s) > 12:
return
if count == 3:
curNum = int(s)
if len(s) >1 and int(s[0]) == 0:
return
if curNum >= 0 and curNum < 256:
ans = ans + "." + s
print ans
self.res.append(ans)
return
length = len(s)
for i in range(1,length+1):
strNum = s[0:i]
curNum = int(strNum)
if len(strNum) > 1 and int(strNum[0]) == 0:
return
if curNum >= 0 and curNum < 256:
if count == 0:
oldAns = ans
ans = ans + strNum
self.findCombination(s[i:],ans,count+1)
ans = oldAns
else:
oldAns = ans
ans = ans + "." + strNum
self.findCombination(s[i:],ans,count+1)
ans = oldAns
else:
break
s = Solution2()
ip = "1111"
s.restoreIpAddresses(ip)
print s.res