일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Daily Challenge
- 파비최
- 개발자
- 미드시청
- 매일
- 프로젝트
- 리얼 클래스
- 화상영어
- 10분
- English
- 스탭퍼
- 영어공부
- 사이드
- 만화도
- 읽기
- 3줄정리
- Writing
- Problem Solving
- 영어원서읽기
- 링피트
- realclass
- 월간
- leetcode
- 쓰릴오브파이트
- 괜찮음
- 30분
- 잡생각
- 뭐든
- FIT XR
- 운동
Archives
- Today
- Total
파비의 매일매일 공부기록
Today's Challenge 본문
https://leetcode.com/problems/sum-of-distances-in-tree/
Sum of Distances in Tree - LeetCode
Sum of Distances in Tree - There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the
leetcode.com
오늘은 좀 어려운 문제.
DFS를 두번이나 돌려야 하네. 백트레킹인가?!
class Solution:
def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
t = collections.defaultdict(set)
res = [0] * n
count = [1] * n
for i, j in edges:
t[i].add(j)
t[j].add(i)
def dfs(root, pre):
for i in t[root]:
if i != pre:
dfs(i, root)
count[root] += count[i]
res[root] += res[i] + count[i]
def dfs2(root, pre):
for i in t[root]:
if i != pre:
res[i] = res[root] - count[i] + n - count[i]
dfs2(i, root)
dfs(0, -1)
dfs2(0, -1)
return res
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
Today's Challenge (0) | 2022.12.24 |
---|---|
Today's Challenge (0) | 2022.12.23 |
Today's Challenge (0) | 2022.12.21 |
Today's Challenge (0) | 2022.12.20 |
Today's Challenge (0) | 2022.12.19 |
Comments