tasks for today:
1. 93.复原IP地址
2. 78.子集
3. 90.子集II
1. 93.复原IP地址
This practice is similar with practcie 131. More complicated point is the requirement on the qualification of IP address, which both require the value of each number segmented by "." (0-255) and the number of segments (4).
one point which is easy leading to error and very sneaky is the datatype conversion between int and str.
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
result = []
path = []
self.backtracking(s, 0, path, result)
return result
def backtracking(self, s, startIndex, path, result):
if (len(path) == 3 and len(s[startIndex:]) >= 4) or len(path) > 4:
return
if startIndex >= len(s) and len(path) == 4:
result.append('.'.join(path))
return
for i in range(startIndex, len(s)):
s_cut = s[startIndex: i+1]
if 0 <= int(s_cut) <= 255:
if s[startIndex] == '0' and (len(s_cut) >= 2):
continue
else:
path.append(s_cut)
self.backtracking(s, i + 1, path, result)
path.pop()
2. 78.子集
IN this practice, the nums has no repetitive elements, which is simple for this configuration, only need to attach the result at every node, which means, in this practice, there is no specific terminal attchment condition.
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()
subSet (子集问题) also belongs to combiantion problem, which indicate the search for each for-loop should start from the startIndex, while in contrast, if in permutation problem, the for-loop will start for zeros.
then another parameters would be in for-loop the self backtracking, use i or i+1, this is decided by if elements can be repetitively used, if yes, then i, otherwise i+1
3. 90.子集II
This practice is a cobination of practice 78 and practice 40:
compared with 78, in this practice, the nums contains repetative elements and teh result is required not containing same result, this means the nums need sorting and an additional "used" list contraining each element's usage status should be engaged as a parameters in backtracking.
compare with practice 40, this need to return all the result from each search node.
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
# this practice is a combination of the practice 78 & 40
result = []
nums.sort()
path = []
used = [False] * len(nums)
self.backtracking(nums, 0, path, result, used)
return result
def backtracking(self, nums, startIndex, path, result, used):
result.append(path[:])
for i in range(startIndex, len(nums)):
if i > 0 and nums[i - 1] == nums[i] and used[i - 1] == False:
continue
used[i] = True
path.append(nums[i])
self.backtracking(nums, i + 1, path, result, used)
path.pop()
used[i] = False