-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0666-path-sum-iv.py
More file actions
43 lines (31 loc) · 1.33 KB
/
0666-path-sum-iv.py
File metadata and controls
43 lines (31 loc) · 1.33 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
# time complexity: O(n)
# space complexity: O(n)
from typing import List
class Solution:
def pathSum(self, nums: List[int]) -> int:
from collections import defaultdict
graph = defaultdict(int)
for num in nums:
depth, pos, val = num//100, (num//10) % 10, num % 10
graph[depth, pos] = val
stack = []
curDepth, curPos = 1, 1
curPathSum = graph[curDepth, curPos]
stack.append((curPathSum, (curDepth, curPos)))
returnedAllPathsSum = 0
while stack:
curPathSum, (curDepth, curPos) = stack.pop()
leftDepth = rightDepth = 1 + curDepth
leftPos, rightPos = 2*curPos-1, 2*curPos
if (leftDepth, leftPos) not in graph and (rightDepth, rightPos) not in graph:
returnedAllPathsSum += curPathSum
else:
if (leftDepth, leftPos) in graph:
leftPathSum = curPathSum + graph[leftDepth, leftPos]
stack.append((leftPathSum, (leftDepth, leftPos)))
if (rightDepth, rightPos) in graph:
rightPathSum = curPathSum + graph[rightDepth, rightPos]
stack.append((rightPathSum, (rightDepth, rightPos)))
return returnedAllPathsSum
nums = [113, 215, 221]
print(Solution().pathSum(nums))