A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0
and 255
(inclusive) and cannot have leading zeros.
"0.1.2.201"
and "192.168.1.1"
are valid IP addresses, but "0.011.255.245"
, "192.168.1.312"
and "192.168@1.1"
are invalid IP addresses.Given a string s
containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s
. You are not allowed to reorder or remove any digits in s
. You may return the valid IP addresses in any order.
Example 1:
Input: s = "25525511135" Output: ["255.255.11.135","255.255.111.35"]
Example 2:
Input: s = "0000" Output: ["0.0.0.0"]
Example 3:
Input: s = "101023" Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
Constraints:
1 <= s.length <= 20
s
consists of digits only.This problem requires finding all valid IP addresses that can be formed by inserting dots into a given string containing only digits. A valid IP address consists of four integers separated by dots, each integer between 0 and 255 (inclusive) and without leading zeros.
The most efficient approach is using Depth-First Search (DFS) or backtracking. The algorithm explores all possible ways to split the input string into four parts, checking the validity of each part at each step.
Base Cases:
i >= n
) and we've successfully split the string into four parts (len(t) == 4
), we've found a valid IP address. Add it to the result list.Recursive Step:
i
.t
.dfs
with the next index (j + 1
).t
(backtracking) to explore other possibilities.t
also takes O(1) space because the size of the list remains fixed at 4 segments.class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
n = len(s)
ans = []
def isValid(segment):
if not segment: return False
if len(segment) > 1 and segment[0] == '0': return False
return 0 <= int(segment) <= 255
def backtrack(index, current_ip):
if index == n and len(current_ip) == 4:
ans.append(".".join(current_ip))
return
if index >= n or len(current_ip) >= 4:
return
for i in range(1, min(4, n - index + 1)):
segment = s[index:index + i]
if isValid(segment):
backtrack(index + i, current_ip + [segment])
backtrack(0, [])
return ans
Other language implementations (Java, C++, Go, TypeScript, C#) follow the same logic with minor syntax adjustments. The core algorithm remains the same depth-first search approach. The crucial part is the isValid
function to ensure that each segment conforms to IP address rules.