requirements

Given a nestedList of integers, nestedList, each element is either an integer or a list. At the same time, the elements in the list can also be integers or another list.

The depth of an integer is the number of layers it has nested inside the list. For example, the value of each integer in a nested list [1,[2,2],[[3],2],1] is its depth.

Return the sum of all depth-weighted integers for this list.

Example 1:

Input: nestedList = [[1,1],2,[1,1]] Output: 10Copy the code

Example 2:

Input: nestedList = [1,[4,[6]] Output: 27 Explanation: A 1 with a depth of 1, a 4 with a depth of 2, and a 6 with a depth of 3. So 1 plus 4 times 2 plus 6 times 3 is 27.Copy the code

Example 3:

NestedList = [0] Output: 0Copy the code

The core code

#class NestedInteger:
# def __init__(self, value=None):
# "" "
# If value is not specified, initializes an empty list.
# Otherwise initializes a single integer equal to value.
# "" "
#
# def isInteger(self):
# "" "
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# "" "
#
# def add(self, elem):
# "" "
# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
# :rtype void
# "" "
#
# def setInteger(self, value):
# "" "
# Set this NestedInteger to hold a single integer equal to value.
# :rtype void
# "" "
#
# def getInteger(self):
# "" "
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# "" "
#
# def getList(self):
# "" "
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# "" "
class Solution:
    def depthSum(self, nestedList: List[NestedInteger]) - >int:
        def Sum(weight,l) :
            if l.isInteger():
                return weight * l.getInteger()
            return sum(Sum(weight + 1,item) for item in l.getList())
        return sum(Sum(1,i) for i in nestedList)
Copy the code

Key issues

Answer:

Using recursive thinking, we keep searching down, and when we see a number, we just do the calculation, and when we see a list, we just do the recursive calculation. That’s a good one.