mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #413 from EnzoSeason/leetcode-93
Update 93.复原IP地址, 添加Python3版本,用了新的剪枝方法
This commit is contained in:
@ -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
|
||||||
|
Reference in New Issue
Block a user