leetcode_339 嵌套列表权重和

977 阅读1分钟

要求

给定一个嵌套的整数列表 nestedList ,每个元素要么是整数,要么是列表。同时,列表中元素同样也可以是整数或者是另一个列表。

整数的 深度 是其在列表内部的嵌套层数。例如,嵌套列表 [1,[2,2],[[3],2],1] 中每个整数的值就是其深度。

请返回该列表按深度加权后所有整数的总和。

示例 1:

image.png

输入:nestedList = [[1,1],2,[1,1]]
输出:10 
解释:因为列表中有四个深度为 21 ,和一个深度为 12

示例 2:

image.png

输入:nestedList = [1,[4,[6]]]
输出:27 
解释:一个深度为 1 的 1,一个深度为 2 的 4,一个深度为 3 的 6。所以,1 + 4*2 + 6*3 = 27

示例 3:

输入:nestedList = [0]
输出:0

核心代码

#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)

image.png

重点问题

解题思路:

使用递归的思路,我们不断向下搜索,遇到数字直接进行计算,遇到列表,递归计算即可。比较不错的一道题。