From d5b0e0ce587df7bb9c627bbad784b71d01098e36 Mon Sep 17 00:00:00 2001 From: Jijie LIU Date: Wed, 16 Jun 2021 14:49:07 +0200 Subject: [PATCH] =?UTF-8?q?Update=2093.=E5=A4=8D=E5=8E=9FIP=E5=9C=B0?= =?UTF-8?q?=E5=9D=80,=20=E6=B7=BB=E5=8A=A0Python3=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=8C=E7=94=A8=E4=BA=86=E6=96=B0=E7=9A=84=E5=89=AA=E6=9E=9D?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0093.复原IP地址.md | 40 +++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index a8b9a215..c47896d9 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -338,6 +338,46 @@ class Solution(object): 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: ```js