题目
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
有效的 IP 地址正好由四个整数(每个整数位于 0 到 255 之间组成),整数之间用 ‘.’ 分隔。
示例:
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
解题思路
backtrace
The core function is defined as f(already_done, remaining_string, remaining_n)
, only when remaining_string
is empty and remaining_n == 0
will we add a solution. Every iteration we only care about the current segment.
Time complexity:
o
(
3
segment length
)
o(3^{\text{segment length}})
o(3segment length), because we would iterate 3 times at each segment, so the time complexity would be exponential.
Space complexity:
o
(
segment length
)
o(\text{segment length})
o(segment length)
代码
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
res = []
def is_valid(segment: str) -> bool:
if len(segment) == 1:
return '0' <= segment <= '9'
if len(segment) == 2:
return '10' <= segment <= '99'
if len(segment) == 3:
return '100' <= segment <= '255'
return False
def helper(already_done: list, remaining_string: str, remaining_n: int) -> None:
if remaining_n == 0 and remaining_string == '':
res.append('.'.join(already_done))
return
if remaining_n == 0 or remaining_string == '':
return
for i in range(min(3, len(remaining_string))):
cur_segment = remaining_string[:i+1]
if is_valid(cur_segment):
helper(already_done + [cur_segment], remaining_string[i+1:], remaining_n - 1)
helper([], s, 4)
return res