Skip to content

Latest commit

 

History

History
58 lines (43 loc) · 1.04 KB

339._Nested_List_Weight_Sum.md

File metadata and controls

58 lines (43 loc) · 1.04 KB

339. Nested List Weight Sum

题目: https://leetcode.com/problems/nested-list-weight-sum/

难度: Easy

思路:

一开始没认真读题,直接上手开写:

class Solution(object):
    def depthSum(self, nestedList):
        """
        :type nestedList: List[NestedInteger]
        :rtype: int
        """
        def dfs(nestedList):
        	for item in nestedList:
        		if item.isInteger():
        			self.res += item.getInteger()
        		else:
        			dfs(item.getList())
        self.res = 0
        dfs(nestedList)
        return self.res

然后注意到要weight by its depth.

AC

class Solution(object):
    def depthSum(self, nestedList):
        """
        :type nestedList: List[NestedInteger]
        :rtype: int
        """
        def dfs(nestedList,depth):
        	for item in nestedList:
        		if item.isInteger():
        			self.res += item.getInteger() * depth
        		else:
        			dfs(item.getList(), depth+1)
        self.res = 0
        dfs(nestedList,1)
        return self.res