zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):093 Restore IP Addresses

    题目来源


    https://leetcode.com/problems/restore-ip-addresses/

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

    For example:
    Given "25525511135",

    return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)


    题意分析


    Input:一串数字

    Output:可能的ip

    Conditions:符合0~255


    题目思路


    用dfs,要注意考虑0.0.0.0的情况,不考虑00.00.00.00这样多个0的


    AC代码(Python)

     1 class Solution(object):
     2     def restoreIpAddresses(self, s):
     3         """
     4         :type s: str
     5         :rtype: List[str]
     6         """
     7         def dfs(s, sub, ips, ip):
     8             if sub == 4:
     9                 if s == "":
    10                     ips.append(ip[1:])
    11                 return
    12             for i in range(1,4):
    13                 if i <= len(s):
    14                     if int(s[:i]) <= 255:
    15                         dfs(s[i:], sub + 1, ips, ip+"."+s[:i])
    16                     if s[0] == "0":
    17                         break
    18         ips = []
    19         dfs(s, 0, ips, "")
    20         return ips
  • 相关阅读:
    cstc2018 混合果汁
    CF1086E Beautiful Matrix
    AT2000 Leftmost Ball
    CF1208E Let Them Slide
    CF1208D Restore Permutation
    【置顶】博客公告
    [NOI2015]软件包管理器
    【noip2018】积木大赛
    几天连测总结
    【ZJOI2007】棋盘制作
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5455820.html
Copyright © 2011-2022 走看看