93.复原IP地址
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
result = []
self.backtracking(s, result, [], 0)
return result
def backtracking(self, s, result, path, startIndex):
if len(path) == 4:
if startIndex == len(s):
result.append(".".join(path))
return
for i in range(startIndex, len(s)):
if int(s[startIndex:i+1]) > 255 or (len(s[startIndex:i+1]) > 1 and s[startIndex]=='0'):
continue
path.append(s[startIndex:i+1])
self.backtracking(s, result, path, i+1)
path.pop()
看了题解之后,可以把判断是否有效提出来成为一个函数,在path等于3的时候就直接得到最后一个数值进行判断
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
result = []
self.backtracking(s, result, [], 0)
return result
def backtracking(self, s, result, path, startIndex):
if len(path) == 3:
if self.is_valid(s, startIndex, len(s)-1):
path.append(s[startIndex:])
result.append(".".join(path))
path.pop()
return
for i in range(startIndex, len(s)):
if not self.is_valid(s, startIndex, i):
continue
path.append(s[startIndex:i+1])
self.backtracking(s, result, path, i+1)
path.pop()
def is_valid(self, s, start, end):
if start > end:
return False
if s[start] == '0' and start != end:
return False
return 0 <= int(s[start:end+1]) <= 255
78.子集
没有终止条件,其它完全套用模板
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = []
self.backtracking(nums, result, [], 0)
return result
def backtracking(self, nums, result, path, startIndex):
result.append(path[:])
for i in range(startIndex, len(nums)):
path.append(nums[i])
self.backtracking(nums, result, path, i+1)
path.pop()
90.子集II
使用索引去重
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
self.backtracking(nums, result, [], 0)
return result
def backtracking(self, nums, result, path, startIndex):
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, result, path, i+1)
path.pop()
使用used去重,这道题使用used意义不大
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
used = [False] * len(nums)
self.backtracking(nums, result, [], 0, used)
return result
def backtracking(self, nums, result, path, startIndex, used):
result.append(path[:])
for i in range(startIndex, len(nums)):
if i > 0 and nums[i] == nums[i-1] and not used[i-1]:
continue
path.append(nums[i])
used[i] = True
self.backtracking(nums, result, path, i+1, used)
path.pop()
used[i] = False