题目描述
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
示例:
示例:
输入: “25525511135”
输出: [“255.255.11.135”, “255.255.111.35”]
解题思路
DFS。搭配较多的剪枝可加快速度。
代码
Python 3.6
[Python] 纯文本查看 复制代码
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
length = len(s)
if length < 4 or length > 12:
return []
res = []
self.__dfs(s, 0, length, [], res)
return res
def __dfs(self, s, start, length, path, res):
blank = 4 - len(path)
if blank == 0:
if start >= length:
res.append(".".join(path.copy()))
return
if (length - start < blank) or (length - start > 3 * blank):
# 剩下的数字比空还少 或 比3*空还多
return
for i in range(1, 4):
end = start + i
if end > length or int(s[start:end]) > 255 or (i > 1 and s[start:end][0] == "0"):
# 不合法:超过255、非单个数字且首位为0
break
path.append(s[start:end])
self.__dfs(s, end, length, path, res)
path.pop()
|
本文深入探讨了如何通过深度优先搜索(DFS)算法解决复原IP地址的问题,提供了Python实现代码,并详细解释了剪枝策略以提高算法效率。
1万+

被折叠的 条评论
为什么被折叠?



