注意点&感悟:
- 加油!
题目链接:93. 复原 IP 地址
自己独立写的代码:
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
res = []
self.backtracking(s,0,[],res)
return res
def backtracking(self,s,start_index,path,result):
# 退出条件1,不满足的
if len(path) > 4:
return
# 退出条件2 找到满足要的
if len(path) == 4 and start_index == len(s): # 等于4 且 切到末尾了
result.append(".".join(path))
# 核心
for i in range(start_index,len(s)):
# 判断合法性 s[start_index:i+1]
if self.is_valid(s[start_index:i+1]):
path.append(s[start_index:i+1])
self.backtracking(s,i+1,path,result)
path.pop()
def is_valid(self,s):
if s[0] == "0" and len(s) > 1:
return False
if int(s) > 255:
return False
return True