[Leetcode]@python 93. Restore IP Addresses
2016-02-23 16:23
701 查看
题目链接
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 k-近邻算法
- Python练习-- slice
- Python练习-- loop
- Python练习-- list and tuple
- Python练习-- iterator
- Python练习-- condition
- [Leetcode]@python 92. Reverse Linked List II
- Python subprocess模块总结
- Python练习--character
- [解决] python WindowsError: [Error 3]
- Eclipse搭建Python开发环境+Python中文处理
- [Leetcode]@python 91. Decode Ways
- Python学习笔记_判断和循环
- Windows下Python开发环境搭建及 Python的HelloWorld示例
- python内置模块(四)
- python之文件编码转换
- 安装ipython import path error
- [备忘]Sublime Text 3 Python编辑环境搭建
- python升级
- python正则表达式基础篇