Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]
. (Order does not matter)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
ans = []
self.dfs(ans,s,4,[])
return ['.'.join(x) for x in ans]
def dfs(self,ans,s,k,temp):
if len(s) > 3*k:
return []
if k == 0:
ans.append(temp[:])
else:
for i in range(min(3,len(s)-k+1)):
if i == 2 and int(s[:3]) > 255 or i > 0 and int(s[0]) == 0:
continue
self.dfs(ans,s[i+1:],k-1,temp+[s[:i+1]])