3. 无重复字符的最长子串 滑动窗口问题
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
#滑动窗口
max_len,hashmap =0,set()
start =0
#定义窗口的首尾两端,滑动窗口
for end in range(len(s)):
hashmap.add(s[end])
if len(hashmap) == end-start+1:
max_len =max(max_len,end-start+1)
while end-start+1 >len(hashmap):
start+=1
hashmap=set(s[start:end+1])
return max_len
797. 所有可能的路径 图论入门,深搜和回溯类似,回溯三部曲确定返回值,中止条件,单层的处理,并且可以将问题抽象成树结构,深搜也类似。
class Solution:
def __init__(self):
self.result = []
self.path = [0]
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
if not graph: return []
self.dfs(graph, 0)
return self.result
def dfs(self, graph, root: int):
if root == len(graph) - 1: # 成功找到一条路径时
# ***Python的list是mutable类型***
# ***回溯中必须使用Deep Copy***
self.result.append(self.path[:])
return
for node in graph[root]: # 遍历节点n的所有后序节点
self.path.append(node)
self.dfs(graph, node)
self.path.pop() # 回溯