Skip to content

Commit 01490da

Browse files
authored
Update 0093.复原IP地址.md
python3代码修正和补充注释
1 parent e447076 commit 01490da

File tree

1 file changed

+40
-25
lines changed

1 file changed

+40
-25
lines changed

problems/0093.复原IP地址.md

Lines changed: 40 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -342,32 +342,47 @@ class Solution:
342342
```
343343

344344
python3:
345-
```python
346-
class Solution(object):
347-
def restoreIpAddresses(self, s):
348-
"""
349-
:type s: str
350-
:rtype: List[str]
351-
"""
352-
ans = []
353-
path = []
354-
def backtrack(path, startIndex):
355-
if len(path) == 4:
356-
if startIndex == len(s):
357-
ans.append(".".join(path[:]))
358-
return
359-
for i in range(startIndex+1, min(startIndex+4, len(s)+1)): # 剪枝
360-
string = s[startIndex:i]
361-
if not 0 <= int(string) <= 255:
362-
continue
363-
if not string == "0" and not string.lstrip('0') == string:
364-
continue
365-
path.append(string)
366-
backtrack(path, i)
367-
path.pop()
345+
```python3
346+
class Solution:
347+
def __init__(self):
348+
self.result = []
368349

369-
backtrack([], 0)
370-
return ans```
350+
def restoreIpAddresses(self, s: str) -> List[str]:
351+
'''
352+
本质切割问题使用回溯搜索法,本题只能切割三次,所以纵向递归总共四层
353+
因为不能重复分割,所以需要start_index来记录下一层递归分割的起始位置
354+
添加变量point_num来记录逗号的数量[0,3]
355+
'''
356+
self.result.clear()
357+
if len(s) > 12: return []
358+
self.backtracking(s, 0, 0)
359+
return self.result
360+
361+
def backtracking(self, s: str, start_index: int, point_num: int) -> None:
362+
# Base Case
363+
if point_num == 3:
364+
if self.is_valid(s, start_index, len(s)-1):
365+
self.result.append(s[:])
366+
return
367+
# 单层递归逻辑
368+
for i in range(start_index, len(s)):
369+
# [start_index, i]就是被截取的子串
370+
if self.is_valid(s, start_index, i):
371+
s = s[:i+1] + '.' + s[i+1:]
372+
self.backtracking(s, i+2, point_num+1) # 在填入.后,下一子串起始后移2位
373+
s = s[:i+1] + s[i+2:] # 回溯
374+
else:
375+
# 若当前被截取的子串大于255或者大于三位数,直接结束本层循环
376+
break
377+
378+
def is_valid(self, s: str, start: int, end: int) -> bool:
379+
if start > end: return False
380+
# 若数字是0开头,不合法
381+
if s[start] == '0' and start != end:
382+
return False
383+
if not 0 <= int(s[start:end+1]) <= 255:
384+
return False
385+
return True
371386
```
372387

373388

0 commit comments

Comments
 (0)