디시인사이드 갤러리

마이너 갤러리 이슈박스, 최근방문 갤러리

갤러리 본문 영역

1519. Number of Nodes in the Sub-Tree~

개발뉴비갤로그로 이동합니다. 2023.01.12 21:01:36
조회 29 추천 0 댓글 0
														

https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/

 

Number of Nodes in the Sub-Tree With the Same Label - LeetCode

Number of Nodes in the Sub-Tree With the Same Label - You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]). The edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree. Return an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i. A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.   Example 1: [https://assets.leetcode.com/uploads/2020/07/01/q3e1.jpg] Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd" Output: [2,1,1,1,1,1,1] Explanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree. Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself). Example 2: [https://assets.leetcode.com/uploads/2020/07/01/q3e2.jpg] Input: n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb" Output: [4,2,1,1] Explanation: The sub-tree of node 2 contains only node 2, so the answer is 1. The sub-tree of node 3 contains only node 3, so the answer is 1. The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2. The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4. Example 3: [https://assets.leetcode.com/uploads/2020/07/01/q3e3.jpg] Input: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab" Output: [3,2,1,1,1]   Constraints: * 1 <= n <= 105 * edges.length == n - 1 * edges[i].length == 2 * 0 <= ai, bi < n * ai != bi * labels.length == n * labels is consisting of only of lowercase English letters.

leetcode.com



class Solution:
    def dfs(self, start, graph, visit, pts, label):
        pts[start][label[start]] += 1  
        for next in graph[start]:
            if visit[next] == 0:
                visit[next] = 1
                self.dfs(next, graph, visit, pts, label)
                for j in range(26):
                    pts[start][j] += pts[next][j]    

    def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
        pts = [[0 for i in range(26)] for j in range(n)]
        label = [ord(s) - ord('a') for s in labels]
        visit = [0 for _ in range(n)]
        graph = [[] for _ in range(n)]
        for x, y in edges:
            graph[x].append(y)
            graph[y].append(x)
        visit[0] = 1
        self.dfs(0, graph, visit, pts, label)
        return [pts[i][label[i]] for i in range(n)]


뭔가 깔끔하게 푸는 방법이 있나 고민했지만

그냥 26개 알파벳 전부 저장하는 트리dp 말곤 떠오르지 않았다.

추천 비추천

0

고정닉 0

0

댓글 영역

전체 댓글 0
본문 보기

하단 갤러리 리스트 영역

왼쪽 컨텐츠 영역

갤러리 리스트 영역

갤러리 리스트
번호 제목 글쓴이 작성일 조회 추천
설문 2025년 가장 기억에 남는 인터넷 이슈는? 운영자 25/12/22 - -
333 3355. Zero Array Transformation I 흑화뉴비갤로그로 이동합니다. 05.20 53 0
332 2918. Minimum Equal Sum of Two Arrays Af 흑화뉴비갤로그로 이동합니다. 05.10 21 0
331 2033. Minimum Operations to Make a Uni-V 흑화뉴비갤로그로 이동합니다. 03.28 45 0
330 2401. Longest Nice Subarray 흑화뉴비갤로그로 이동합니다. 03.19 38 0
329 1079. Letter Tile Possibilities 흑화뉴비갤로그로 이동합니다. 02.18 45 0
328 1718. Construct the Lexicographically La 흑화뉴비갤로그로 이동합니다. 02.16 28 0
327 1910. Remove All Occurrences of a Substr 흑화뉴비갤로그로 이동합니다. 02.11 29 0
326 2381. Shifting Letters II 흑화뉴비갤로그로 이동합니다. 01.05 42 0
323 2471. Minimum Number of Operations to So 흑화뉴비갤로그로 이동합니다. 24.12.25 31 0
322 773. Sliding Puzzle 흑화뉴비갤로그로 이동합니다. 24.11.27 30 0
321 3243. Shortest Distance After Road Addit 흑화뉴비갤로그로 이동합니다. 24.11.27 23 0
320 1233. Remove Sub-Folders from the Filesy 흑화뉴비갤로그로 이동합니다. 24.10.29 30 0
319 2684. Maximum Number of Moves in a Grid 흑화뉴비갤로그로 이동합니다. 24.10.29 31 0
318 2501. Longest Square Streak in an Array 흑화뉴비갤로그로 이동합니다. 24.10.29 43 0
317 3043. Find the Length of the Longest Com 흑화뉴비갤로그로 이동합니다. 24.09.24 38 0
316 1514. Path with Maximum Probability 흑화뉴비갤로그로 이동합니다. 24.08.27 37 0
315 264. Ugly Number II 흑화뉴비갤로그로 이동합니다. 24.08.19 35 0
314 2285. Maximum Total Importance of Roads 흑화뉴비갤로그로 이동합니다. 24.06.28 47 0
313 1552. Magnetic Force Between Two Balls 흑화뉴비갤로그로 이동합니다. 24.06.20 38 0
312 1482. Minimum Number of Days to Make m B 흑화뉴비갤로그로 이동합니다. 24.06.19 41 0
311 523. Continuous Subarray Sum 흑화뉴비갤로그로 이동합니다. 24.06.09 41 0
310 리트코드 갤러리 5월 이벤트 우승자 공지 [1] 진척갤로그로 이동합니다. 24.06.08 65 0
309 1208. Get Equal Substrings Within Budget 흑화뉴비갤로그로 이동합니다. 24.05.28 41 0
308 1608. Special Array With X Elements Grea 흑화뉴비갤로그로 이동합니다. 24.05.28 33 0
307 552. Student Attendance Record II 흑화뉴비갤로그로 이동합니다. 24.05.28 32 0
306 2597. The Number of Beautiful Subsets [1] 흑화뉴비갤로그로 이동합니다. 24.05.24 57 0
305 78. Subsets 흑화뉴비갤로그로 이동합니다. 24.05.21 32 0
304 1863. Sum of All Subset XOR Totals 흑화뉴비갤로그로 이동합니다. 24.05.21 36 0
302 1325. Delete Leaves With a Given Value 흑화뉴비갤로그로 이동합니다. 24.05.18 37 0
301 2331. Evaluate Boolean Binary Tree 흑화뉴비갤로그로 이동합니다. 24.05.18 28 0
298 3075. Maximize Happiness of Selected Chi 흑화뉴비갤로그로 이동합니다. 24.05.12 25 0
297 786. K-th Smallest Prime Fraction 흑화뉴비갤로그로 이동합니다. 24.05.12 29 0
296 506. Relative Ranks 흑화뉴비갤로그로 이동합니다. 24.05.08 38 0
295 2816. Double a Number Represented as a L 흑화뉴비갤로그로 이동합니다. 24.05.08 25 0
294 2487. Remove Nodes From Linked List 흑화뉴비갤로그로 이동합니다. 24.05.06 26 0
293 79. Word Search o오어o(14.37) 24.05.04 29 0
292 45. Jump Game II o오어o(14.37) 24.05.04 35 0
291 881. Boats to Save People o오어o(14.37) 24.05.04 29 0
290 2441. Largest Positive Integer That Exis 흑화뉴비갤로그로 이동합니다. 24.05.02 28 0
289 2997. Minimum Number of Operations to Ma 흑화뉴비갤로그로 이동합니다. 24.05.01 24 0
288 2000. Reverse Prefix of Word 흑화뉴비갤로그로 이동합니다. 24.05.01 34 0
287 리트코드 갤러리 5월 이벤트 공지 [3] 진척갤로그로 이동합니다. 24.04.28 97 0
282 백준 1260. DFS와 BFS 차근차근춘식이(211.234) 24.04.23 46 0
277 206. Reverse Linked List 흑화뉴비갤로그로 이동합니다. 24.03.21 47 0
276 1669. Merge In Between Linked Lists 흑화뉴비갤로그로 이동합니다. 24.03.20 30 0
275 57. Insert Interval 흑화뉴비갤로그로 이동합니다. 24.03.18 31 0
274 2485. Find the Pivot Integer 흑화뉴비갤로그로 이동합니다. 24.03.13 24 0
273 1750. Minimum Length of String After Del 흑화뉴비갤로그로 이동합니다. 24.03.06 26 0
272 451. Sort Characters By Frequency 흑화뉴비갤로그로 이동합니다. 24.02.07 40 0
271 49. Group Anagrams 흑화뉴비갤로그로 이동합니다. 24.02.06 35 0
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

디시미디어

디시이슈

1/2