Hard
,Array
,Tree
,Graph
,Union Find
There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n
nodes numbered from 0
to n - 1
and exactly n - 1
edges.
You are given a 0-indexed integer array vals
of length n
where vals[i]
denotes the value of the ith node. You are also given a 2D integer array edges
where edges[i]
= [, ] denotes that there exists an undirected edge connecting nodes and .
A good path is a simple path that satisfies the following conditions:
The starting node and the ending node have the same value.
All nodes between the starting node and the ending node have values less than or equal to the starting node (i.e. the starting node's value should be the maximum value along the path).
Return the number of distinct good paths.
Note that a path and its reverse are counted as the same path. For example, 0 -> 1
is considered to be the same as 1 -> 0
. A single node is also considered as a valid path.
Example 1:
Example 2:
Example 3:
Constraints:
n
== vals.length
n
<= 3 * 104vals[i]
<= 105edges.length
== n
- 1edges[i].length
== 2n
edges
represents a valid tree.XD Jan 15, 2023
Time: n
為node數, m
為node中不同的值
Extra Space: