作者: 负雪明烛
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. Mac下source tree 下的安装

    安装时出现了以下错误,解决方法 git -c diff.mnemonicprefix=false -c core.quotepath=false -c credential.helper=source ...

  2. 学习java 7.11

     学习内容: 泛型定义格式:<类型> 优点:把运行时期的问题提前到编译期间:避免了强制类型转换   泛型方法:public class Fanxing { public <T> ...

  3. 一起手写吧!promise.all

    Promise.all 接收一个 promise 对象的数组作为参数,当这个数组里的所有 promise 对象全部变为resolve或 有 reject 状态出现的时候,它才会去调用 .then 方法 ...

  4. TCP中的TIME_WAIT状态

    TIME_WAIT的存在有两大理由 1.可靠地实现TCP全双工连接的终止 2.允许老的可重复分节在网络中消失. 对于理由1,我们知道TCP结束需要四次挥手,若最后一次的客户端的挥手ACK丢失(假设是客 ...

  5. C++基本函数的调用优化(构造、拷贝构造、赋值)

    合理的函数可提升时间和空间的利用率 //Test1.h #include<iostream> using namespace std; struct ST { private: int a ...

  6. EasyExcel读写Excel

    使用过 poi 的开发同学可能都有此体会,每次都要写一坨代码,最后的代码如下面一样: 这样的代码是不是又臭又长?当字段数量多的时候,一不小心还容易写错.阿粉还记得当初使用 poi 导出一个二十多字段的 ...

  7. 【Linux】【Services】【SaaS】Spinnaker

    1. 简介 1.1. 说明: Spinnaker 是 Netflix 的开源项目,是一个持续交付平台,它定位于将产品快速且持续的部署到多种云平台上.Spinnaker 通过将发布和各个云平台解耦,来将 ...

  8. ORACLE 数据块PCTFREE和PCTUSED

    PCTFREE表示一个数据块可用空间小于PCTFREE时,该数据块不在被记录在FREELIST中,即不能插入新数据. PCTUSED表示一个数据块已经用空间如果小于PCTUSED时,该数据块才会被重新 ...

  9. 【编程思想】【设计模式】【创建模式creational】Borg/Monostate

    Python版 https://github.com/faif/python-patterns/blob/master/creational/borg.py #!/usr/bin/env python ...

  10. Redis,Memcache,MongoDb的特点与区别

    Redis Redis 简介 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库. Redis 与其他 key - value 缓存产品有以下三个特点: Redis支 ...