算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 复原IP地址,我们先来看题面:
https://leetcode-cn.com/problems/restore-ip-addresses/
Given a string s containing only digits, return all possible valid IP addresses that can be obtained from s. You can return them in any order.
A valid IP address consists of exactly four integers, each integer is between 0 and 255, separated by single dots and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses and "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses.
题意
示例 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"]
解题
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
n = len(s)
if n < 4 or n > 12:
return []
ret = []
def dfs(cur, ips):
# 如果递归结束,并且ips当中刚好存了4个ip
# 则生成答案
if cur >= n:
if len(ips) == 4:
ret.append('.'.join(ips[:]))
return
# 遍历下一个ip是几位
for i in range(cur, min(cur+3, n)):
# 如果超过1位但是第一位是0,那么非法
if s[cur] == '0' and i > cur:
return
# ip必须小于等于255
num = int(s[cur: i+1])
if num > 255:
return
# 回溯
ips.append(s[cur: i+1])
dfs(i+1, ips)
ips.pop()
dfs(0, [])
return ret
上期推文:
本文分享自微信公众号 - 程序IT圈(DeveloperIT)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
来源:oschina
链接:https://my.oschina.net/u/2898531/blog/4714398