原题
https://leetcode.cn/problems/restore-ip-addresses/description/
思路
回溯法
复杂度
时间:O(n!)
空间:O(n!)
Python代码
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
ans = []
def isValidIP(sub):
if 0 <= int(sub) <= 255:
# 包含前导0
if len(sub) > 1 and sub[0] == '0':
return False
else:
return True
else:
return False
def dfs(start, path):
# 返回条件
if start == len(s) and len(path) == 4:
ans.append('.'.join(path))
return
if start == len(s) and len(path) != 4:
return
for j in range(start, len(s)):
sub = s[start: j+1]
if isValidIP(sub):
path.append(sub)
dfs(j+1, path)
# 还原
path.pop()
dfs(0, [])
return ans
Go代码
func restoreIpAddresses(s string) []string {
var ans []string
var isValidIP = func(sub string) bool {
n, _ := strconv.Atoi(sub)
if 0 <= n && n <= 255 {
// 包含前导0
if len(sub) > 1 && sub[0] == '0' {
return false
} else {
return true
}
} else {
return false
}
}
// 匿名函数
var dfs func(int, []string)
dfs = func(start int, path []string) {
// 返回条件
if start == len(s) && len(path) == 4 {
addr := strings.Join(path, ".")
ans = append(ans, addr)
return
}
if start == len(s) && len(path) != 4 {
return
}
for j := start; j < len(s); j++ {
sub := s[start : j+1]
if isValidIP(sub) {
path = append(path, sub)
dfs(j+1, path)
// 还原
path = path[:len(path)-1]
}
}
}
dfs(0, []string{})
return ans
}
508

被折叠的 条评论
为什么被折叠?



