作者: 负雪明烛
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. Docker镜像相关操作

    批量导入镜像 ll *.tgz|awk '{print $NF}'|sed -r 's#(.*)#docker load -i \1#' |bash 批量打tag docker images | se ...

  2. 学习java 7.10

    学习内容: List 集合:有序集合,用户可以精确控制列表中每个元素的插入位置 List 集合特点:有序:存储和取出的元素顺序一致 可重复:存储的元素可以重复 增强for循环:简化数组和 Collec ...

  3. 【leetcode】121. Best Time to Buy and Sell Stock(股票问题)

    You are given an array prices where prices[i] is the price of a given stock on the ith day. You want ...

  4. MediaPlayer详解

    [1]MediaPlayer 详细使用细则 [2]MediaPlayer使用详解_为新手准备 [3]MediaPlayer 概览

  5. mybatis-plus条件构造用is开头的Boolean类型字段时遇到的问题

    is打头的Boolean字段导致的代码生成器与lambda构造器的冲突 https://gitee.com/baomidou/mybatis-plus/issues/I171DD?_from=gite ...

  6. OSGI 理论知识

    下面列出了主要的控制台命令: 表 1. Equinox OSGi 主要的控制台命令表 类别 命令 含义 控制框架 launch 启动框架 shutdown 停止框架 close 关闭.退出框架 exi ...

  7. mysql数据库备份脚本一例

    例子,mysql数据库备份脚本.vim mysql.sh #!/bin/bash DAY=`date +%Y-%m-%d` //日期以年月日显示并赋予DAY变量 SIZE=`du -sh /var/l ...

  8. Linux下部署Java项目(jetty作为容器)常用脚本命令

    startup.sh #!/bin/bash echo $(basename $(pwd)) "jetty started" cd jetty nohup java -Xmx8g ...

  9. 【Java多线程】ExecutorService和ThreadPoolExecutor

    ExecutorService Java.util.concurrent.ExecutorService接口代表一种异步执行机制,它能够在后台执行任务.因此ExecutorService与thread ...

  10. JSP常用内置对象

    1.request 1.1getAttribute(String name) 2.getAttributeName() 3.getCookies() 4.getCharacterEncoding() ...