博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode]Restore IP Addresses @ Python
阅读量:7193 次
发布时间:2019-06-29

本文共 1161 字,大约阅读时间需要 3 分钟。

原题地址: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

 

转载地址:http://lgvkm.baihongyu.com/

你可能感兴趣的文章
AlertDialog错误
查看>>
Tiling 简单递推+大数
查看>>
iOS开发UI篇—Quartz2D使用(绘制基本图形)
查看>>
java web servlet
查看>>
几个博客
查看>>
v4l2
查看>>
JS倒计时
查看>>
(new Function("return " + json))();
查看>>
mscrm 4.0 报表服务器报错
查看>>
SVM原理简介
查看>>
TLV----Demo讲解
查看>>
Mermaid js与流程图、甘特图..
查看>>
java 调度框架quartz
查看>>
hadoop exit code 退出码含义
查看>>
[C#基础知识系列]专题十:全面解析可空类型
查看>>
什么是.Net的异步机制(线程间通信) - step 5
查看>>
Lambda应用设计模式
查看>>
解决svn异常报错“”cleanup failed to process the following paths …… previous operation has not finished”...
查看>>
富文本框--FreeTextBox的使用
查看>>
koa2使用阿里云oss的nodejs sdk实现上传图片
查看>>