主要内容
- 子集,组合,排序,去重
- 分割
题目
93.复原IP地址
思路分析
分割
代码
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
# 字符串的分割
def __init__(self):
self.res = []
self.path = []
def restoreIpAddresses(self, s: str) -> List[str]:
self.backtracking(s, 0)
return self.res
def backtracking(self, s, startindex):
if startindex >= len(s) and len(self.path) >= 4:
if startindex == len(s) and len(self.path) == 4:
self.res.append(".".join(self.path))
return
for i in range(startindex, len(s)):
temp = s[startindex:i+1]
# 判断c是否满足,前导0,且值在[0,255]之间
if len(str(int(temp))) == len(temp) and int(temp) >= 0 and int(temp) <= 255:
self.path.append(temp)
self.backtracking(s, i + 1)
self.path.pop()
else:
continue
# leetcode submit region end(Prohibit modification and deletion)
78.子集
思路分析
先收集结果
代码
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def __init__(self):
self.res = []
self.path = []
def subsets(self, nums: List[int]) -> List[List[int]]:
self.backtracking(nums, 0)
return self.res
def backtracking(self, nums, startindex):
# 收集结果
self.res.append(self.path[:])
# 终止条件,可省略
if startindex >= len(nums):
return
for i in range(startindex, len(nums)):
self.path.append(nums[i])
self.backtracking(nums, i+1)
self.path.pop()
# leetcode submit region end(Prohibit modification and deletion)
90.子集II
思路分析
- 先收集结果
- 排序去重
代码
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def __init__(self):
self.res = []
self.path = []
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
self.backtracking(sorted(nums),0)
return self.res
def backtracking(self, nums, startindex):
self.res.append(self.path[:])
if startindex >= len(nums):
return
for i in range(startindex, len(nums)):
if i > startindex and nums[i] == nums[i-1]:
continue
self.path.append(nums[i])
self.backtracking(nums, i+1)
self.path.pop()
# leetcode submit region end(Prohibit modification and deletion)