364. Nested List Weight Sum II

Nested List Weight Sum II - LeetCode You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. The depth of an integer is the number of lists that it is inside of. For example, the nested list [1,[2,2],[[3],2],1] has each integer’s value set to its depth. Let maxDepth be the maximum depth of any integer. The weight of an integer is maxDepth - (the depth of the integer) + 1. Return the sum of each integer in nestedList multiplied by its weight.

Example 1:

Input: nestedList = [[1,1],2,[1,1]] Output: 8 Explanation: Four 1’s with a weight of 1, one 2 with a weight of 2. 11 + 11 + 22 + 11 + 1*1 = 8

  • code
class Solution:
    def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
        depth = 0
        depth_value = defaultdict(int)
        while nestedList:
            depth += 1
            num_removed = []
            for l in nestedList:
                if l.isInteger():
                    depth_value[depth] += l.getInteger()
                else:
                    num_removed.extend(l.getList())
            nestedList = num_removed
        res = 0
        for cur_depth, value in depth_value.items():
            res += value * (depth - cur_depth + 1)
        return res