一、继续学习回溯算法:
1.leetcode题目 93. 复原 IP 地址 - 力扣(LeetCode)
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
path = []
result = []
def is_valid(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
def dfs(path,result,s_index,s):
if s_index == len(s) and len(path) == 4:
result.append(".".join(path))
return
if len(path) > 4:
return
for i in range(s_index,min(s_index+3,len(s))):
if is_valid(s,s_index,i):
sub = s[s_index:i+1]
path.append(sub)
dfs(path,result,i+1,s)
path.pop()
dfs(path,result,0,s)
return result
2.leetcode题目 78. 子集 - 力扣(LeetCode)
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
path = []
result = []
def dfs(nums,s_index,path,result):
result.append(path[:])
for i in range(s_index,len(nums)):
path.append(nums[i])
dfs(nums,i+1,path,result)
path.pop()
dfs(nums,0,path,result)
return result
3.leetcode题目 90. 子集 II - 力扣(LeetCode)
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
path = []
result = []
def dfs(nums,path,result,s_index):
result.append(path[:])
for i in range(s_index,len(nums)):
if i>s_index and nums[i] == nums[i-1]: ##很关键,有重复元素时的处理操作
continue
path.append(nums[i])
dfs(nums,path,result,i+1)
path.pop()
nums.sort()
dfs(nums,path,result,0)
return result