Python solution with detailed explanation


  • 0
    G

    Solution

    Nested List Weight Sum https://leetcode.com/problems/nested-list-weight-sum/

    • We use a simple DFS to compute the nested list weight.The outermost list has level 1.
    • Beyond that we just need to loop across all items in the nested list. If item is an integer, update the weighted sum. Otherwise make a recursive call with the nested list and updated level.
    class Solution(object):
        def depthSum(self, nestedList):
            """
            :type nestedList: List[NestedInteger]
            :rtype: int
            """
            self.d_sum = 0
            self.helper(nestedList, 1)
            return self.d_sum
        
        def helper(self, nestedList, level):
            for x in nestedList:
                if x.isInteger():
                    self.d_sum = self.d_sum + x.getInteger()*level
                else:
                    self.helper(x.getList(), level+1)
            return
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.