Restore IP Addresses
这道题也是分段式的回溯,需要注意一个是必须分成四段,先导零只有在0一个字符单独分一段时才允许,其他情况直接break,另外每段字符的长度不可能超过三位,最后每一段字符都必须在0到255之间
class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
res = []
self.helper(s, 0, len(s), 0, '', res)
return res
def helper(self, string, start, end, count, tmp, res):
if count == 4:
if start >= end:
res.append(tmp[:-1])
return
for i in xrange(start, end):
if (string[start] == '0' and i > start) or i - start > 2:
break
if 0 <= int(string[start : i + 1]) <= 255:
self.helper(string, i + 1, end, count + 1, tmp + string[start : i + 1] + '.', res)