题目描述
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
示例:
输入: “25525511135”
输出: [“255.255.11.135”, “255.255.111.35”]
解法:回溯(Python)
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
res = []
def backtrace(cnt = 0, ip = '', s = ''):
if cnt == 4:
if s == '':
res.append(ip[:-1])
return
if len(s) > 0:
backtrace(cnt + 1, ip + s[0] + '.', s[1:])
if len(s) > 1 and s[0] != '0':
backtrace(cnt + 1, ip + s[:2] + '.', s[2:])
if len(s) > 2 and s[0] != '0' and int(s[0:3]) < 256:
backtrace(cnt + 1, ip + s[:3] + '.', s[3:])
backtrace(0, '', s)
return res