디시인사이드 갤러리

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

갤러리 본문 영역

1519. Number of Nodes in the Sub-Tree~

개발뉴비갤로그로 이동합니다. 2023.01.12 21:01:36
조회 28 추천 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 - -
85 909. Snakes and Ladders 이벤트ㅇㅅㅇ(219.251) 23.01.24 49 0
83 997. Find the Town Judge 이벤트ㅇㅅㅇ(219.251) 23.01.23 45 0
82 997. Find the Town Judge [1] 개발뉴비갤로그로 이동합니다. 23.01.23 74 0
81 백준 9996번 키비갤로그로 이동합니다. 23.01.23 56 0
78 마갤 입문함 [2] 키비갤로그로 이동합니다. 23.01.22 61 0
77 131. Palindrome Partitioning [1] 개발뉴비갤로그로 이동합니다. 23.01.22 59 0
75 93. Restore IP Addresses [1] 개발뉴비갤로그로 이동합니다. 23.01.21 72 0
74 Longest Palindromic Substring 5번 o오어o(14.37) 23.01.21 30 0
73 Restore IP Addresses 93번 o오어o(14.37) 23.01.21 39 0
72 안녕하세요 오늘부터 릿코 달리게씁니당 [2] 조르디(112.170) 23.01.21 55 0
71 491. Non-decreasing Subsequences [1] 개발뉴비갤로그로 이동합니다. 23.01.21 57 0
70 974. Subarray Sums Divisible by K [1] 개발뉴비갤로그로 이동합니다. 23.01.19 44 0
69 926. Flip String to Monotone Increasing [1] 개발뉴비갤로그로 이동합니다. 23.01.17 43 0
68 57. Insert Interval [1] 개발뉴비갤로그로 이동합니다. 23.01.17 39 0
66 트리 문제 두 개 개빡치네; 개발뉴비갤로그로 이동합니다. 23.01.15 48 0
65 1061. Lexicographically Smallest ~ 개발뉴비갤로그로 이동합니다. 23.01.15 42 0
64 여기 갤럼들은 전부 해외취업 준비중? [2] EvenAsura갤로그로 이동합니다. 23.01.14 107 0
1519. Number of Nodes in the Sub-Tree~ 개발뉴비갤로그로 이동합니다. 23.01.12 28 0
62 1443. Minimum Time to Collect All Apples 개발뉴비갤로그로 이동합니다. 23.01.11 41 0
59 230111 데일리 꽃지갤로그로 이동합니다. 23.01.11 68 0
58 100. Same Tree 개발뉴비갤로그로 이동합니다. 23.01.10 35 0
56 220110 데일리 꽃지갤로그로 이동합니다. 23.01.10 41 0
53 144. Binary Tree Preorder Traversal 개발뉴비갤로그로 이동합니다. 23.01.09 41 0
52 230109 데일리 꽃지갤로그로 이동합니다. 23.01.09 31 0
51 리트코드 4번 [4] o오어o(222.121) 23.01.09 66 0
50 리트코드 3번 o오어o(222.121) 23.01.09 25 0
49 220108 데일리 꽃지갤로그로 이동합니다. 23.01.08 55 0
48 68. Text Justification ㅇㅇ(12.50) 23.01.08 37 0
47 3번문제 코드 딱 한줄만 알려준다 ㅇㅇ(218.234) 23.01.08 38 0
46 코딩 테스트 tdd로 하시는 분 [1] TS(119.64) 23.01.07 61 0
45 가스스테이션(데일리) o오어o(222.121) 23.01.07 52 0
44 230107 데일리 [1] 꽃지갤로그로 이동합니다. 23.01.07 55 0
43 134. Gas Station 개발뉴비갤로그로 이동합니다. 23.01.07 48 0
42 1833. Maximum Ice Cream Bars 개발뉴비갤로그로 이동합니다. 23.01.06 58 0
41 230106 데일리 꽃지갤로그로 이동합니다. 23.01.06 50 0
38 오늘의 릿코드 Minimum Number of Arrows~ 개발뉴비갤로그로 이동합니다. 23.01.05 41 0
36 230105 데일리 [3] 꽃지갤로그로 이동합니다. 23.01.05 65 0
35 2244. Minimum Rounds 이거 푸는데 TS(119.64) 23.01.05 37 0
34 데일리 문제 어떻게 알아봄...? [1] TS(119.64) 23.01.05 40 0
33 230104 데일리 [2] 꽃지갤로그로 이동합니다. 23.01.04 88 0
31 Minimum Rounds to Complete All Task [1] 개발뉴비갤로그로 이동합니다. 23.01.04 103 0
30 944. Delete Columns to Make Sorted in TS ㅇㅇ(119.64) 23.01.04 43 0
29 백준 17726 Inheritance 꽃지갤로그로 이동합니다. 23.01.04 58 0
28 백준 14503번 로봇 청소기 개발뉴비갤로그로 이동합니다. 23.01.04 94 0
23 오늘의 릿코드 Delete Columns to Make Sorted [2] 개발뉴비갤로그로 이동합니다. 23.01.03 79 0
22 오늘의 데일리 [3] 꽃지갤로그로 이동합니다. 23.01.03 84 0
19 리트코드 해보면서 느낀 점 ㅇㅇ(119.64) 23.01.03 91 0
18 어쨌든 TS로 대문자 판별하기 문제 풀었는데 ㅇㅇ(119.64) 23.01.03 47 0
17 저는 js로 할게요 [5] ㅇㅇ(119.64) 23.01.03 80 0
16 오늘의 릿코드 Detect Capital 개발뉴비갤로그로 이동합니다. 23.01.02 61 1
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

디시미디어

디시이슈

1/2