1、题目描述
https://leetcode-cn.com/problems/restore-ip-addresses/
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
有效的 IP 地址正好由四个整数(每个整数位于 0 到 255 之间组成),整数之间用 '.' 分隔。
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
2、代码详解
暴力
class Solution(object):
def restoreIpAddresses(self, s):
n = len(s)
res = []
# 判读是否满足ip的条件
def helper(tmp):
# 每位是在0~255之间, 不能出现以0开头的两位以上数字
if not tmp or (tmp[0] == "0" and len(tmp) > 1) or int(tmp) > 255:
return False
return True
# 三个循环,把数字分成四份
for i in range(3):
for j in range(i + 1, i + 4):
for k in range(j + 1, j + 4):
if i < n and j < n and k < n:
tmp1 = s[:i + 1]
tmp2 = s[i + 1:j + 1]
tmp3 = s[j + 1:k + 1]
tmp4 = s[k + 1:]
# print(tmp1, tmp2, tmp3, tmp4)
# all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE
# map(function, iterable, ...),返回包含每次 function 函数返回值的新列表
if all(map(helper, [tmp1, tmp2, tmp3, tmp4])):
res.append(tmp1 + "." + tmp2 + "." + tmp3 + "." + tmp4)
return res
ss = "25525511135"
s = Solution()
print(s.restoreIpAddresses(ss)) # ['255.255.11.135', '255.255.111.35']
all()https://www.runoob.com/python/python-func-all.html
map()https://www.runoob.com/python/python-func-map.html
回溯
https://leetcode-cn.com/problems/restore-ip-addresses/solution/bao-li-he-hui-su-by-powcai/