题目:
题目链接: https://leetcode-cn.com/problems/restore-ip-addresses/
解题思路:
"所有可能" = 回溯 + 剪枝
剪枝条件为:
-
如果已遍历完,则判断是否合法
-
如果当前已有4位ip,但是字符串未遍历完
-
如果当前位置字符串长度大于1,并且第一位字符是'0'
代码实现:
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