Union Find
Leetcode
Algorithm Princeton
API example
Time Complexity:
union find with path compression: O(N + M*lgN), M union find operations on a set of N objects. If M >> N, it will goes to ~ O(1)
Space Complexity:
O(N)
DFS on Graph
Practice:
找爸爸以及和它的关系
leetcode 299
给定node之间的关系,求所有两两之间的关系
套路:
- 建图,找出每个node的neighbors
- 用dfs遍历图,存每个node和root之间的关系
模板:
mem = {}
def dfs(cur, root, rate):
if cur in mem: # 已经遍历过了,所以可以return
return
mem[cur] = [root, rate]
for nei, nei_rate in neighbors[cur]:
dfs(root, nei, rate * nei_rate)