leetcode_364 加权嵌套序列和 II

409 阅读2分钟

要求

给你一个整数嵌套列表 nestedList ,每一个元素要么是一个整数,要么是一个列表(这个列表中的每个元素也同样是整数或列表)。

整数的 深度 取决于它位于多少个列表内部。例如,嵌套列表 [1,[2,2],[[3],2],1] 的每个整数的值都等于它的 深度 。令 maxDepth 是任意整数的 最大深度 。

整数的 权重 为 maxDepth - (整数的深度) + 1 。

将 nestedList 列表中每个整数先乘权重再求和,返回该加权和。

示例 1:

image.png

输入:nestedList = [[1,1],2,[1,1]]
输出:8
解释:41 在深度为 1 的位置, 一个 2 在深度为 2 的位置。
1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 8

示例 2:

image.png

输入:nestedList = [1,[4,[6]]]
输出:17
解释:一个 1 在深度为 3 的位置, 一个 4 在深度为 2 的位置,一个 6 在深度为 1 的位置。 
1*3 + 4*2 + 6*1 = 17

核心代码

# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#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 depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
        record = [0 for _ in range(10000)]
        res = 0
        self.max_weight = 0
        def work(weight,l):
            self.max_weight = max(weight,self.max_weight)
            if l.isInteger():
                record[weight] += l.getInteger()
            else:
                for item in l.getList():
                    work(weight + 1,item)
        
        for item in nestedList:
            work(1,item)
        
        for i in range(1,self.max_weight+1):
            res += (self.max_weight + 1 -i ) * record[i]
        return res

image.png

解题思路:这道题和我们339题很相似,解题手法基本相同,这不过是我们需要我们自己维护一个权重和数字的字典,注意work函数的两个作用,第一个作用,得到最深的层次,第二个是将深度和数值,做成了一个字典,遇到数值,直接添加,遇到列表的话,我们直接递归循环处理即可,最后注意下计算权重的公式,对数据进行计算即可。