zoukankan      html  css  js  c++  java
  • [Leetcode]@python 93. 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)

    题目大意

    输入一个字符串,给出所有的可能IP的集合

    解题思路

    使用dfs求解。可将题目理解成在一个字符串中加入3个挡板,得到四个子字符串的值都小于255.

    代码

    class Solution(object):
        def restoreIpAddresses(self, s):
            """
            :type s: str
            :rtype: List[str]
            """
            def dfs(s, sub, ips, ip):
                if sub == 4:  # should be 4 parts
                    if s == '':
                        ips.append(ip[1:])  # remove first '.'
                    return
                for i in range(1, 4):  # the three ifs' order cannot be changed!
                    if i <= len(s):  # if i > len(s), s[:i] will make false!!!!
                        if int(s[:i]) <= 255:
                            dfs(s[i:], sub + 1, ips, ip + '.' + s[:i])
                        if s[0] == '0':
                            break  # make sure that res just can be '0.0.0.0' and remove like '00'
    
            ips = []
            dfs(s, 0, ips, '')
            return ips
    
  • 相关阅读:
    python之高阶函数
    [第二版]多线程的发送与接收
    基本函数与结构
    unp.h
    gdb调试命令
    System V共享内存区
    Posix 共享内存区
    System V信号量
    Posix 信号量
    记录锁
  • 原文地址:https://www.cnblogs.com/slurm/p/5210353.html
Copyright © 2011-2022 走看看