-
Notifications
You must be signed in to change notification settings - Fork 43
/
nested-list-weight-sum-ii.py
67 lines (57 loc) · 1.8 KB
/
nested-list-weight-sum-ii.py
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# V0
# V1
# https://blog.csdn.net/qq508618087/article/details/51743408
# V1'
# https://www.jiuzhang.com/solution/nested-list-weight-sum-ii/#tag-highlight-lang-python
class Solution:
"""
@param nestedList: a list of NestedInteger
@return: the sum
"""
def depthSumInverse(self, nestedList):
# Write your code here.
listq = nestedList
qintq = [] # queue of integer queue
while listq:
intq = [] # this level integer queue
newlistq = [] # next level list queue
while listq:
ni = listq.pop()
if ni.isInteger():
intq.append(ni.getInteger())
else:
newlistq.extend(ni.getList())
qintq.append(intq)
listq = newlistq
wsum = 0 # weight sum
w = 0 # weight
while qintq:
w += 1
intq = qintq.pop()
while intq:
wsum += w * intq.pop()
return wsum
# V2
# Time: O(n)
# Space: O(h)
class Solution(object):
def depthSumInverse(self, nestedList):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
def depthSumInverseHelper(list, depth, result):
if len(result) < depth + 1:
result.append(0)
if list.isInteger():
result[depth] += list.getInteger()
else:
for l in list.getList():
depthSumInverseHelper(l, depth + 1, result)
result = []
for list in nestedList:
depthSumInverseHelper(list, 0, result)
sum = 0
for i in reversed(range(len(result))):
sum += result[i] * (len(result) - i)
return sum