您的位置:首页 > 编程语言 > Python开发

[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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: