来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/restore-ip-addresses
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
有效的 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 地址。
示例 1:
输入:s = "25525511135" 输出:["255.255.11.135","255.255.111.35"]
示例 2:
输入:s = "0000" 输出:["0.0.0.0"]
示例 3:
输入:s = "1111" 输出:["1.1.1.1"]
示例 4:
输入:s = "010010" 输出:["0.10.0.10","0.100.1.0"]
示例 5:
输入:s = "101023" 输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
解题思路:第一个想法就是每次选择一个、两个、或者三个数字并以它们为基础进行递归直到由四个整数构成一个地址并判断是否有效,如果有效就加入result,AC代码如下:
class Solution: def restoreIpAddresses(self, s: str) -> List[str]: result = [] temp = "" length = len(s) self.calculate(s, 0, temp, result, length, 0) for i in range(len(result)): result[i] = result[i][:len(result[i]) - 1] return result def calculate(self, s: str, location: int, temp: str, result: List[str], length: int, count: int): if count == 4: if location == length: result.append(temp) return else: if location < length and s[location] == "0": temp += "0." self.calculate(s, location + 1, temp, result, length, count + 1) else: self.calculate(s, location + 1, temp + s[location:location + 1] + ".", result, length, count + 1) if location + 2 <= length: self.calculate(s, location + 2, temp + s[location:location + 2] + ".", result, length, count + 1) if location + 3 <= length and s[location:location + 3] <= "255": self.calculate(s, location + 3, temp + s[location:location + 3] + ".", result, length, count + 1)