https://leetcode.com/problems/restore-ip-addresses/
求 all possible solutions 肯定是dfs backtracking
参考http://www.cnblogs.com/zuoyuan/p/3768112.html
http://blog.csdn.net/linhuanmars/article/details/24683699
my code:
class Solution(object):
def isValid(self, s):
if s == '' or len(s) > 3:
return False
if len(s) > 1 and s[0] == '0':
return False
if 0<= int(s) <=255:
return True
return False
def dfs(self, s, slice_num, subres, res):
if slice_num == 0 and len(s) == 0:
res.append(subres[1:])
return
#elif len(s) == 0:#这个可以不要,不会出现第一段很大的情况
# return
else:
for i in xrange(1, 4):#第一段不可能长度超过3
if self.isValid(s[:i]) and i <= len(s):#注意这里要i<= len(s)这个条件,否则会出现重复解,否则也不能有s[i:]
self.dfs(s[i:], slice_num - 1, subres + '.' + s[:i], res)
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
if len(s) > 12: return []
res = []
self.dfs(s, 4, '',res)
return res