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)
The question is to give a string with a reasonable IP address and a list containing all reasonable IP addresses. We know that the IP address is composed of four parts and the reasonable range is 0.0.0.0 ~ 255.255.255.255.
The Code mainly has two functions:
Isvalid -- check whether it is reasonable. If it starts with 0, the string must be 0; otherwise, it must be greater than 0 and less than 255;
DFS-use the Deep Search Method to search for all possible combinations;
Therefore, the DFS method is used to search for all possible combinations. If valid is used during each search to the fourth part, this is a reasonable IP address and is added to the result list.
Pay attention to the details of generating IP addresses and Add. Or something.
The Python code is as follows:
1 class RestoreIPAddress: 2 3 def isValid(self, src): 4 if src[0] == ‘0‘: 5 return src == ‘0‘ 6 return 255 >= int(src) > 0 7 8 def dfs(self, src, temp, res, count): 9 if count == 3 and self.isValid(src):10 res.append(temp + src)11 return12 for i in range(1, min(4, len(src))):13 sub = src[0:i]14 if self.isValid(sub):15 self.dfs(src[i:], temp + sub + ‘.‘, res, count + 1)16 17 def restoreIpAddresses(self, s):18 if len(s) < 4 or len(s) > 12:19 return []20 res = []21 self.dfs(s, "", res, 0)22 # print(res)23 return res24 25 p = RestoreIPAddress()26 p.restoreIpAddresses("0000")
Leetcode -- Restore IP addresses