zoukankan      html  css  js  c++  java
  • [leetcode]Restore IP Addresses @ Python

    原题地址:https://oj.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)

    解题思路:这个明显是用dfs来解决。来一段精致简练的代码吧。

    代码:

    class Solution:
        # @param s, a string
        # @return a list of strings
        def restoreIpAddresses(self, s):
            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
  • 相关阅读:
    换教室
    [国家集训队]礼物
    【模板】扩展卢卡斯(学习笔记)
    Desert King
    绿豆蛙的归宿
    Dropping tests
    [SDOI2013]随机数生成器
    佳佳的fib
    [USACO10OPEN]水滑梯Water Slides
    强大的XML
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3768112.html
Copyright © 2011-2022 走看看