【LeetCode】93. Restore IP Addresses 解题报告(Python & C++)
作者: 负雪明烛
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++)的更多相关文章
- leetcode 93. Restore IP Addresses(DFS, 模拟)
题目链接 leetcode 93. Restore IP Addresses 题意 给定一段序列,判断可能组成ip数的所有可能集合 思路 可以采用模拟或者DFS的想法,把总的ip数分成四段,每段判断是 ...
- LeetCode: Restore IP Addresses 解题报告
Restore IP Addresses My Submissions Question Solution Given a string containing only digits, restore ...
- [LeetCode] 93. Restore IP Addresses 复原IP地址
Given a string containing only digits, restore it by returning all possible valid IP address combina ...
- LeetCode : 93. Restore IP Addresses
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAABZ4AAAHUCAYAAAC6Zj2HAAAMFGlDQ1BJQ0MgUHJvZmlsZQAASImVlw
- leetcode 93 Restore IP Addresses ----- java
Given a string containing only digits, restore it by returning all possible valid IP address combina ...
- 93.Restore IP Addresses(M)
93.Restore IP Addresses Medium 617237FavoriteShare Given a string containing only digits, restore it ...
- 【LeetCode】93. Restore IP Addresses
Restore IP Addresses Given a string containing only digits, restore it by returning all possible val ...
- 93. Restore IP Addresses
题目: Given a string containing only digits, restore it by returning all possible valid IP address com ...
- 【leetcode】Restore IP Addresses
Restore IP Addresses Given a string containing only digits, restore it by returning all possible val ...
随机推荐
- Oracle-trunc函数、round 函数、ceil函数和floor函数---处理数字函数使用
0.round函数 按照指定小数位数进行四舍五入运算. SELECT ROUND( number, [ decimal_places ] ) FROM DUAL #number : 待处理数值 de ...
- 数据库(database)介绍
0.数据定义:除了文本类型的数据,图像.音乐.声音都是数据. 数据分类:结构化数据.非结构化数据.1.数据库定义:"电子化的文件柜","数据仓库".数据库是一个 ...
- Python中的随机采样和概率分布(二)
在上一篇博文<Python中的随机采样和概率分布(一)>(链接:https://www.cnblogs.com/orion-orion/p/15647408.html)中,我们介绍了Pyt ...
- 一文搞懂指标采集利器 Telegraf
作者| 姜闻名 来源|尔达 Erda 公众号 导读:为了让大家更好的了解 MSP 中 APM 系统的设计实现,我们决定编写一个<详聊微服务观测>系列文章,深入 APM 系统的产品.架构 ...
- C语言内自定义汇编函数&调用约定
探究如何在C语言里直接自写汇编函数 裸函数 裸函数与普通函数的区别 普通函数在经过编译器编译时,编译器自动生成保护现场,恢复现场等反汇编代码 当我们想要自己实现函数内部的汇编代码时,就可以告诉汇编器不 ...
- c学习 - 第七章:数组
7.3.6 字符串处理函数 (1).puts(字符数组) 字符串输出到终端 (2).gets(字符数组) 从标准输入获取字符串(包括空格) (3).strcat(字符数组1,字符数组2) 连接两个字符 ...
- 哪里可以下载支付宝demo或者sdk
http://club.alipay.com/read-htm-tid-9976972.html 这里有所有的demo和sdk包括移动产品的demo.在他的论坛里面呢 真心恶心啊.不放到主页.
- vue2 安装打包部署
vue2项目搭建记录 mkdir -p /opt/wks/online_pre/1006cd /opt/wks/online_pre/1006mkdir hongyun-ui /opt/code/vu ...
- Spring(4):Mybatis和Spring整合
第一步:创建数据库 MySQL代码 1 CREATE DATABASE `mybatis` ; 2 3 USE `mybatis`; 4 5 CREATE TABLE `user` ( 6 `id` ...
- vue-cli2嵌入html
1.使用iframe <!-- 相对路径/绝对路径 --> <iframe src="../../../static/zsw.html"></ifra ...