Skip to content

Commit 7037ed2

Browse files
authored
Create nested_list_weight_sum.py
1 parent c67fc15 commit 7037ed2

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

nested_list_weight_sum.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
This is the interface that allows for creating nested lists.
3+
You should not implement it, or speculate about its implementation
4+
5+
class NestedInteger(object):
6+
def isInteger(self):
7+
# @return {boolean} True if this NestedInteger holds a single integer,
8+
# rather than a nested list.
9+
10+
def getInteger(self):
11+
# @return {int} the single integer that this NestedInteger holds,
12+
# if it holds a single integer
13+
# Return None if this NestedInteger holds a nested list
14+
15+
def getList(self):
16+
# @return {NestedInteger[]} the nested list that this NestedInteger holds,
17+
# if it holds a nested list
18+
# Return None if this NestedInteger holds a single integer
19+
"""
20+
21+
22+
class Solution(object):
23+
# @param {NestedInteger[]} nestedList a list of NestedInteger Object
24+
# @return {int} an integer
25+
@staticmethod
26+
def _depthSum(nestedList, count, level=1): # 递归,level记录深度
27+
for i in nestedList:
28+
if i.isInteger():
29+
count[0] += i.getInteger() * level
30+
else:
31+
Solution._depthSum(i.getList(), count, level+1)
32+
33+
def depthSum(self, nestedList):
34+
# Write your code here
35+
count = [0]
36+
Solution._depthSum(nestedList, count)
37+
return count[0]
38+
39+
# easy: https://www.lintcode.com/problem/nested-list-weight-sum

0 commit comments

Comments
 (0)