作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/restore-ip-addresses/description/

题目描述

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

题目大意

题目中给了一个仅有数字组成的字符串,要求这个字符串能构成的合法IP组合。

解题方法

回溯法

我是按照Tag刷的,当然知道这个题是回溯法了。。其实只要看到所有的组合,一般都是用回溯。

第一遍超时,原因是没有找到合理的剪枝!!这就是回溯法最难的地方:剪枝!

当然了,看出了测试用例是一个特别长的由1组成的字符串,仅仅这一个测试用例超时,所以我加上了len(s)和12的判断就ok了。所以有了下面的版本:

代码如下:

class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
if len(s) > 12:
return []
res = []
self.dfs(s, [], res)
return res def dfs(self, s, path, res):
if not s and len(path) == 4:
res.append('.'.join(path))
return
for i in range(1, 4):
if i > len(s):
continue
number = int(s[:i])
if str(number) == s[:i] and number <= 255:
self.dfs(s[i:], path + [s[:i]], res)

看到了题目中有别的同学的剪枝方法特别好,那就是每次dfs的时候都去检查一下所有的字符串的长度是不是能满足在最多4个3位数字组成,果然速度提升了很多:

class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
res = []
self.dfs(s, [], res)
return res def dfs(self, s, path, res):
if len(s) > (4 - len(path)) * 3:
return
if not s and len(path) == 4:
res.append('.'.join(path))
return
for i in range(min(3, len(s))):
curr = s[:i+1]
if (curr[0] == '0' and len(curr) >= 2) or int(curr) > 255:
continue
self.dfs(s[i+1:], path + [s[:i+1]], res)

二刷的时候,使用的C++,同样需要使用合理的剪枝,提交的时候有一次WA,原因是没有考虑0开头的整数是不合法的。代码如下:

class Solution {
public:
vector<string> restoreIpAddresses(string s) {
if (s.size() > 12) return {};
vector<string> res;
helper(s, res, {}, 0);
return res;
}
void helper(const string& s, vector<string>& res, vector<string> path, int start) {
if (start > s.size() || path.size() > 4) return;
if (start == s.size() && path.size() == 4) {
res.push_back(path[0] + '.' + path[1] + '.' + path[2] + '.' + path[3]);
return;
}
for (int i = 1; i <= 3; i++) {
string sub = s.substr(start, i);
if (sub.size() == 0 || (sub.size() > 1 && sub[0] == '0') || stoi(sub) > 255) continue;
path.push_back(sub);
helper(s, res, path, start + i);
path.pop_back();
}
}
};

日期

2018 年 6 月 11 日 —— 今天学科三在路上跑的飞快~
2018 年 12 月 22 日 —— 今天冬至

【LeetCode】93. Restore IP Addresses 解题报告(Python & C++)的更多相关文章

  1. leetcode 93. Restore IP Addresses(DFS, 模拟)

    题目链接 leetcode 93. Restore IP Addresses 题意 给定一段序列,判断可能组成ip数的所有可能集合 思路 可以采用模拟或者DFS的想法,把总的ip数分成四段,每段判断是 ...

  2. LeetCode: Restore IP Addresses 解题报告

    Restore IP Addresses My Submissions Question Solution Given a string containing only digits, restore ...

  3. [LeetCode] 93. Restore IP Addresses 复原IP地址

    Given a string containing only digits, restore it by returning all possible valid IP address combina ...

  4. LeetCode : 93. Restore IP Addresses

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAABZ4AAAHUCAYAAAC6Zj2HAAAMFGlDQ1BJQ0MgUHJvZmlsZQAASImVlw

  5. leetcode 93 Restore IP Addresses ----- java

    Given a string containing only digits, restore it by returning all possible valid IP address combina ...

  6. 93.Restore IP Addresses(M)

    93.Restore IP Addresses Medium 617237FavoriteShare Given a string containing only digits, restore it ...

  7. 【LeetCode】93. Restore IP Addresses

    Restore IP Addresses Given a string containing only digits, restore it by returning all possible val ...

  8. 93. Restore IP Addresses

    题目: Given a string containing only digits, restore it by returning all possible valid IP address com ...

  9. 【leetcode】Restore IP Addresses

    Restore IP Addresses Given a string containing only digits, restore it by returning all possible val ...

随机推荐

  1. LearnPython_week3

    函数说明 1 # -*- coding:utf-8 -*- 2 # Author:Wong Du 3 4 5 ###函数, 6 # 能避免代码重复, 7 # 方便代码修改等操作 8 def wong( ...

  2. Flume消费内外网分流配置的Kafka时遇到的坑

    网上有铺天盖地的文章,介绍如何将Kafka同时配置成公网地址.内网地址,以实现内外网分流,看着都很成功. 但我们通过Flume消费一个配置了内外网分流的Kafka(版本0.10.1)集群时遇到了坑,却 ...

  3. 从 ClickHouse 到 ByteHouse:实时数据分析场景下的优化实践

    本文来自火山引擎公众号,原文发布于2021-09-06. 近日,字节跳动旗下的企业级技术服务平台火山引擎正式对外发布「ByteHouse」,作为 ClickHouse 企业版,解决开源技术上手难 &a ...

  4. C#点击按钮添加标签

    <asp:Button ID="button1" runat="server" Text="创建" onclick="But ...

  5. 网卡命令ifconfig

    • ifconfig • service network restart • ifdown eth0 • ifdown eth0 #linux下run networkexport USER=lizhe ...

  6. redis 之 哨兵

    #:编译安装redis4.0 [root@master ~]# tar xf redis-4.0.14.tar.gz [root@master ~]# cd redis-4.0.14/ [root@m ...

  7. VUE页面实现加载外部HTML方法

    前后端分离,后端提供了接口.但有一部分数据,比较产品说明文件,是存在其他的服务器上的.所以,在页面显示的时候,如果以页面内嵌的形式显示这个说明文件.需要搞点事情以达到想要的效果.本文主要和大家介绍VU ...

  8. C++内存管理:简易内存池的实现

    什么是内存池? 在上一篇 C++内存管理:new / delete 和 cookie中谈到,频繁的调用 malloc 会影响运行效率以及产生额外的 cookie, 而内存池的思想是预先申请一大块内存, ...

  9. 2、Spring的IOC标签介绍以及实例

    一.Spring_ioc配置文件bean标签介绍 1. bean标签 名称:bean 类型:标签 归属:beans标签 作用:定义spring中的资源,受此标签定义的资源将受到spring控制 格式: ...

  10. 使用IDEA整合spring4+spring mvc+hibernate

    配置文件 spring-mvc.xml 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans x ...