Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example
Input: “25525511135”
Output: [“255.255.11.135”, “255.255.111.35”]
Solution
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
def dfs(s, path, ret):
if len(s)>3*(4-len(path)):
return
if not s and len(path)==4:
ret.append('.'.join(path))
return
for i in range(1,4):
if i>len(s):
continue
if str(int(s[:i]))==s[:i] and int(s[:i])<=255:
dfs(s[i:], path+[s[:i]], ret)
ret = []
dfs(s, [], ret)
return ret