topic:
Topic links: https://leetcode-cn.com/problems/restore-ip-addresses/
Problem-solving ideas:
"All possible" = + prune back
Pruning conditions:
-
If you have been traversed, it is determined whether or not legitimate
-
If you currently have 4 ip, but the string is not complete traversal
-
If the current position of a character string length is greater than 1, and is a '0'
Code:
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
def create_res(start, s, res, path):
if start >= len(s):
if 4 == len(path):
res.append('.'.join(path))
return
elif 4 <= len(path):
return
for index in range(1, 4):
if start + index > len(s):
break
curr_str = s[start:start + index]
int_val = int(curr_str)
if int_val < 0 or int_val > 255:
continue
elif 1 < len(curr_str) and '0' == curr_str[0]:
break
path.append(curr_str)
create_res(start + index, s, res, path)
path.pop()
if 12 < len(s):
return []
res = []
create_res(0, s, res, [])
return res