Re: [闲聊] 每日leetcode

楼主: dont   2024-08-31 10:53:16
每日重复了 来写个每周
666. Path Sum IV
## 思路
1
2 3
4 5 6 7
每个点的 idx = 2^(depth-1) + (pos-1)
* 父节点 = idx // 2
* 左子节点 = 2*idx
* 右子节点 = 2*idx + 1
先把数字转成idx跟val存到dict
再找leaves并加总path sum
## Code
```python
class Solution:
def pathSum(self, nums: List[int]) -> int:
mapping = {}
for num in nums:
depth, pos, digit = num // 100, (num % 100) // 10, num % 10
idx = 2 ** (depth-1) + pos-1
mapping[idx] = digit
res = 0
for i in mapping:
if (2*i) in mapping or (2*i+1) in mapping:
continue
while i:
res += mapping[i]
i >>= 1
return res
```
作者: Smallsh (Smallsh)   2024-08-31 10:54:00
大师
作者: sustainer123 (caster)   2024-08-31 10:54:00
大师
作者: argorok (s.green)   2024-08-31 10:55:00
大师
作者: DJYOMIYAHINA (通通打死)   2024-08-31 11:20:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com