# """# 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# The result is undefined 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# The result is undefined if this NestedInteger holds a single integer# :rtype List[NestedInteger]# """class Solution: def depthSum(self, nestedList: List[NestedInteger]) -> int: def dfs(nested_list, depth): """深度优先搜索计算加权和""" total_sum = 0 for item in nested_list: if item.isInteger(): # 如果是整数,将其值乘以当前深度后累加 total_sum += item.getInteger() * depth else: # 如果是列表,递归处理子列表,深度加 1 total_sum += dfs(item.getList(), depth + 1) return total_sum # 从深度 1 开始递归计算 return dfs(nestedList, 1)