93.复原IP地址
照例先写一版很辣鸡但是能AC的:
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
res = []
def isValid(a):
if len(a) > 1 and a[0] == '0':
return False
if int(a) > 255:
return False
return True
def dfs(path, start):
if len(path) == 4 and start >= len(s):
res.append('.'.join(path))
return
for end in range(start, len(s)):
if isValid(s[start: end + 1]):
dfs(path + [s[start: end + 1]], end + 1)
dfs([], 0)
return res
剪枝:
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
res = []
def isValid(segment):
if len(segment) > 1 and segment[0] == '0':
return False
return 0 <= int(segment) <= 255
def dfs(path, start):
if len(path) == 4:
if start == len(s):
res.append('.'.join(path))
return
for end in range(start + 1, min(start + 4, len(s) + 1)):
segment = s[start:end]
if isValid(segment):
dfs(path + [segment], end)
if 4 <= len(s) <= 12:
dfs([], 0)
return res
78.子集
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
def dfs(path, start):
res.append(path[:])
for i in range(start, len(nums)):
dfs(path + [nums[i]], i + 1)
dfs([], 0)
return res
90.子集II
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
def dfs(path, start):
res.append(path)
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue
dfs(path + [nums[i]], i + 1)
dfs([], 0)
return res
后两题比较简单,只给代码了

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



