Merge pull request #413 from EnzoSeason/leetcode-93

Update 93.复原IP地址, 添加Python3版本,用了新的剪枝方法
This commit is contained in:
程序员Carl
2021-06-21 09:58:26 +08:00
committed by GitHub

View File

@ -338,6 +338,46 @@ class Solution(object):
return ans``` return ans```
``` ```
```python3
class Solution:
def __init__(self) -> None:
self.s = ""
self.res = []
def isVaild(self, s: str) -> bool:
if len(s) > 1 and s[0] == "0":
return False
if 0 <= int(s) <= 255:
return True
return False
def backTrack(self, path: List[str], start: int) -> None:
if start == len(self.s) and len(path) == 4:
self.res.append(".".join(path))
return
for end in range(start + 1, len(self.s) + 1):
# 剪枝
# 保证切割完s没有剩余的字符。
if len(self.s) - end > 3 * (4 - len(path) - 1):
continue
if self.isVaild(self.s[start:end]):
# 在参数处,更新状态,实则创建一个新的变量
# 不会影响当前的状态当前的path变量没有改变
# 因此递归完不用path.pop()
self.backTrack(path + [self.s[start:end]], end)
def restoreIpAddresses(self, s: str) -> List[str]:
# prune
if len(s) > 3 * 4:
return []
self.s = s
self.backTrack([], 0)
return self.res
```
JavaScript JavaScript
```js ```js