93. 复原 IP 地址
解题思路:模拟分割的每种情况,首先满足前导不为0,s中间不存在非数值,且每段取值区间在[0,255]
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
result = []
self.backtracking(s, 0, 0, "", result)
return result
def backtracking(self, s, startIndex, pointNum, current, result):
# 如果已经分割为 4 段,检查最后一段是否合法
if pointNum == 3:
if self.is_valid(s, startIndex, len(s) - 1):
# 加入第四段并添加到结果中
current += s[startIndex:]
result.append(current)
return
# 从当前位置开始尝试分割
for i in range(startIndex, len(s)):
# 如果该段合法,则继续
if self.is_valid(s, startIndex, i):
sub = s[startIndex:i+1] # 提取子字符串
# 递归调用并增加分割点数量
self.backtracking(s, i + 1, pointNum + 1, current + sub + ".", result)
else:
break # 如果当前段不合法,退出循环
def is_valid(self, s, start, end):
# 检查是否超出范围或前导零
if start > end:
return False
if s[start] == '0' and start != end:
return False
num = int(s[start:end + 1])
return 0 <= num <= 255
78. 子集
解题思路:找出所有切割的可能性,本题没有重复元素
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = []
path = []
self.backtracking(nums, 0, path, result)
return result
def backtracking(self, nums, startIndex, path, result):
result.append(path[:])
for i in range(startIndex, len(nums)):
path.append(nums[i])
self.backtracking(nums, i+1, path, result)
path.pop()
90. 子集 II
解题思路:有重复值,当遇到重复值值应当要跳过,避免造成重复解
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
path = []
result = []
nums.sort()
self.backtracking(nums,0,path,result)
return result
def backtracking(self, nums, startIndex, path, result):
result.append(path[:])
for i in range(startIndex, len(nums)):
if i > startIndex and nums[i] == nums[i-1]:
continue
path.append(nums[i])
self.backtracking(nums, i+1, path,result)
path.pop()