LeetCode 题解工作台

复原 IP 地址

有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0 ),整数之间用 '.' 分隔。 例如: "0.1.2.201" 和 "192.168.1.1" 是 有效 IP 地址,但是 "0.011.255.245" 、 "192.168.1.312" 和 "192.…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 回溯·pruning

bolt

答案摘要

我们定义一个函数 ,表示从字符串 的第 位开始,搜索能够组成的 IP 地址列表。 函数 的执行步骤如下:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 回溯·pruning 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

有效 IP 地址 正好由四个整数(每个整数位于 0255 之间组成,且不能含有前导 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"]

示例 2:

输入:s = "0000"
输出:["0.0.0.0"]

示例 3:

输入:s = "101023"
输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

 

提示:

  • 1 <= s.length <= 20
  • s 仅由数字组成
lightbulb

解题思路

方法一:DFS

我们定义一个函数 dfs(i)dfs(i),表示从字符串 ss 的第 ii 位开始,搜索能够组成的 IP 地址列表。

函数 dfs(i)dfs(i) 的执行步骤如下:

如果 ii 大于等于字符串 ss 的长度,说明已经完成了四段 IP 地址的拼接,判断是否满足四段 IP 地址的要求,如果满足则将当前 IPIP 加入答案。

如果 ii 小于字符串 ss 的长度,此时还需要拼接 IPIP 地址的一段,此时需要确定这一段 IPIP 地址的值。如果该值大于 255255,或者当前位置 ii00ii 之后的若干位的数值大于 00,则说明不满足要求,直接返回。否则,将其加入 IPIP 地址列表,并继续搜索下一段 IPIP 地址。

时间复杂度 O(n×34)O(n \times 3^4),空间复杂度 O(n)O(n)。其中 nn 为字符串 ss 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        def check(i: int, j: int) -> int:
            if s[i] == "0" and i != j:
                return False
            return 0 <= int(s[i : j + 1]) <= 255

        def dfs(i: int):
            if i >= n and len(t) == 4:
                ans.append(".".join(t))
                return
            if i >= n or len(t) >= 4:
                return
            for j in range(i, min(i + 3, n)):
                if check(i, j):
                    t.append(s[i : j + 1])
                    dfs(j + 1)
                    t.pop()

        n = len(s)
        ans = []
        t = []
        dfs(0)
        return ans
speed

复杂度分析

指标
时间complexity is O(M ^ N \cdot N), where M is the maximum segment length (3) and N is the string length, due to recursive exploration. Space complexity is O(M \cdot N) for the recursion stack and temporary segment storage.
空间O(M \cdot N)
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect candidates to handle leading zeros correctly and prune invalid paths.

  • question_mark

    Look for efficient recursive or iterative backtracking rather than brute-force splitting.

  • question_mark

    Watch if candidate avoids unnecessary string copying and joins segments carefully.

warning

常见陷阱

外企场景
  • error

    Not pruning segments larger than 255 leads to TLE.

  • error

    Allowing leading zeros in multi-digit segments generates invalid addresses.

  • error

    Incorrectly handling string bounds when placing dots can cause out-of-range errors.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return only the first k valid IP addresses instead of all.

  • arrow_right_alt

    Count the total number of valid IP addresses without listing them.

  • arrow_right_alt

    Generate IP addresses for a string that may contain non-digit separators, ignoring them in validation.

help

常见问题

外企场景

复原 IP 地址题解:回溯·pruning | LeetCode #93 中等