93. 复原 IP 地址
类似131分割回文子串
def restoreIpAddresses(self, s: str) -> List[str]:
def check(num):
if num.startswith('0') and num != '0':
return False
elif int(num) < 0 or int(num) > 255:
return False
return True
path = []
res = []
def recursion(j):
if j == len(s) and len(path) == 4:
res.append('.'.join(path))
for i in range(j, len(s)):
# 剪枝
if len(path) > 3:
break
sub = s[j:i+1]
if check(sub):
path.append(sub)
recursion(i+1)
path.pop()
recursion(0)
return res
78. 子集
注意无重复元素
def subsets(self, nums: List[int]) -> List[List[int]]:
path = []
res = []
def recursion(j):
if j == len(nums):
res.append(path[:])
return
res.append(path[:])
for i in range(j, len(nums)):
path.append(nums[i])
recursion(i+1)
path.pop()
recursion(0)
return res
90. 子集 II
用起始位置跳过重复点
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
path = []
res = []
nums.sort()
def recursion(j):
if j == len(nums):
res.append(path[:])
return
res.append(path[:])
for i in range(j, len(nums)):
if i > j and nums[i] == nums[i-1]:
continue
path.append(nums[i])
recursion(i+1)
path.pop()
recursion(0)
return res