93. 复原 IP 地址
每日几道leetcode刷刷题!
传送门
题目描述
有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 ‘.’ 分隔。
例如:“0.1.2.201” 和 “192.168.1.1” 是 有效 IP 地址,但是 “0.011.255.245”、“192.168.1.312” 和 “192.168@1.1” 是 无效 IP 地址。
给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 ‘.’ 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。
示例 1:
输入:s = “25525511135”
输出:[“255.255.11.135”,“255.255.111.35”]
代码
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
if len(s) > 12 or len(s) < 4:
return []
result = []
path = []
def isvalid(q):
if q == '0': #q为全零的情况
return True
if q[0] == '0' :
return False
if int(q) > 255 or int(q) < 0:
return False
return True
def backtrack(s, start):
if len(path) == 4 and start == len(s):
result.append('.'.join(path[:]))
return
for i in range(start, len(s)):
if len(s) - start > 3*(4 - len(path)): continue # 剪枝,剩下的字符串大于允许的最大长度则跳过
p = s[start:i+1]
if isvalid(p):
path.append(p)
else:
continue
backtrack(s, i+1)
path.pop()
backtrack(s, 0)
return result
总结
类似的分割问题 传送门