Skip to content

Commit 2198a2d

Browse files
committed
Complete Leetcode 93
1 parent c5e1bdb commit 2198a2d

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Restore IP Addresses
2+
3+
Problem can be found in [here](https://leetcode.com/problems/restore-ip-addresses/)!
4+
5+
### [Solution](/Backtracking/93-RestoreIPAddresses/solution.py): Backtracking
6+
7+
```python
8+
def restoreIpAddresses(s: str) -> List[str]:
9+
def dfs(start: int, candidate: List[str]) -> None:
10+
if start == len(s):
11+
if len(candidate) == 4:
12+
result.append(".".join(candidate))
13+
return
14+
15+
if s[start] == "0":
16+
dfs(start+1, candidate+["0"])
17+
return
18+
19+
for end in range(start+1, min(start+4, len(s)+1)):
20+
address = s[start:end]
21+
if 0 <= int(address) <= 255:
22+
dfs(end, candidate+[address])
23+
24+
result = []
25+
dfs(0, [])
26+
return result
27+
```
28+
29+
Time Complexity: ![O(m^n)](<https://latex.codecogs.com/svg.image?\inline&space;O(m^n)>), Space Complexity: ![O(m*n)](<https://latex.codecogs.com/svg.image?\inline&space;O(m*n)>), where n is the number of splits and m is the digits of each integer.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def restoreIpAddresses(self, s: str) -> List[str]:
6+
def dfs(start: int, candidate: List[str]) -> None:
7+
if start == len(s):
8+
if len(candidate) == 4:
9+
result.append(".".join(candidate))
10+
return
11+
12+
if s[start] == "0":
13+
dfs(start+1, candidate+["0"])
14+
return
15+
16+
for end in range(start+1, min(start+4, len(s)+1)):
17+
address = s[start:end]
18+
if 0 <= int(address) <= 255:
19+
dfs(end, candidate+[address])
20+
21+
result = []
22+
dfs(0, [])
23+
return result

0 commit comments

Comments
 (0)