# """# 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: # 第一次遍历:计算最大深度 max_depth = self.getMaxDepth(nestedList, 1) # 第二次遍历:计算加权和 return self.calculateSum(nestedList, 1, max_depth) def getMaxDepth(self, nestedList: List[NestedInteger], depth: int) -> int: """计算嵌套列表的最大深度""" max_depth = depth for item in nestedList: if item.isInteger(): # 如果是整数,更新最大深度 max_depth = max(max_depth, depth) else: # 如果是列表,递归计算子列表的最大深度 max_depth = max(max_depth, self.getMaxDepth(item.getList(), depth + 1)) return max_depth def calculateSum(self, nestedList: List[NestedInteger], depth: int, max_depth: int) -> int: """计算加权和""" total_sum = 0 for item in nestedList: if item.isInteger(): # 如果是整数,计算其加权贡献 # 权重 = max_depth - depth + 1 weight = max_depth - depth + 1 total_sum += item.getInteger() * weight else: # 如果是列表,递归计算子列表的加权和 total_sum += self.calculateSum(item.getList(), depth + 1, max_depth) return total_sum