93.复原IP地址
解法:回溯
class Solution:
def __init__(self):
self.res = []
def restoreIpAddresses(self, s: str) -> List[str]:
self.res.clear()
if len(s) > 12: return []
self.backtracking(s, 0, 0)
return self.res
def backtracking(self, s: str, startindex: int, pointnum: int) -> None:
if pointnum ==3:
if self.is_valid(s,startindex,len(s)-1):
self.res.append(s[:])
return
for i in range(startindex,len(s)):
if self.is_valid(s,startindex,i):
s = s[:i+1] + '.' +s[i+1:]
self.backtracking(s,i+2,pointnum+1)
s = s[:i+1] + s[i+2:]
else:
continue
def is_valid(self,s,start,end):
if start > end:
return False
if s[start] == '0' and start != end:
return False
if not 0 <= int(s[start:end+1]) <= 255:
return False
return True
78.子集
解法:回溯(收集子集要先于终止条件)
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
path = []
res = []
def backtracking(nums,startindex):
res.append(path[:])
if startindex >= len(nums):
return
for i in range(startindex,len(nums)):
path.append(nums[i])
backtracking(nums,i+1)
path.pop()
backtracking(nums,0)
return res
90.子集II
解法:回溯 + 去重
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
path = []
res = []
nums.sort()
used = len(nums) * [False]
def backtracking(nums,startindex):
res.append(path[:])
if startindex >= len(nums):
return
for i in range(startindex,len(nums)):
if i > 0 and nums[i] == nums[i-1] and used[i-1] == False:
continue
path.append(nums[i])
used[i] = True
backtracking(nums,i+1)
path.pop()
used[i] = False
backtracking(nums,0)
return res