leetcode 339.Nested List Weight Sum

来源:互联网 发布:sql修改列默认值 编辑:程序博客网 时间:2024/05/16 18:14

Nested List Weight Sum

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


Given a nested list of integers, return the sum of all integers in the list weighted by their depth.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example 1:
Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1)

Example 2:
Given the list [1,[4,[6]]], return 27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27)



题目说是吧有这么个list, 问按照list的深度加权,来求出所有元素的和是多少。


比较简单点的解法可以直接count 方括号的深度,开始一个方括号'['就加一,结束一个']'就减一。


但是题目很蛋疼的说,我们这些元素全都是obj,你得调用这些obj得方法。


简单得递归一下就ok了


值得注意的是,一开始的函数没有权重的输入参数,而且给的输入是一个list。

于是不得不重写一个可以递归的函数了。

python代码和要求如下:


#class NestedInteger(object):
#    def isInteger(self):
#        """
#        @return True if this NestedInteger holds a single integer, rather than a nested list.
#        :rtype bool
#        """
#
#    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(object):
    def depthSum(self, nestedList):
        """
        :type nestedList: List[NestedInteger]
        :rtype: int
        """
        result = 0
        if not nestedList:
            return result
        for i in nestedList:
            result+=self.weightSum(i,1)
            # already a list of nested integers
        return result
    
    def weightSum(self, nestedList, level):
        result = 0
        if not nestedList:
            return result
        if nestedList.isInteger():
            return level*nestedList.getInteger()
        else:
            nestedList_new = nestedList.getList()
            for i in nestedList_new:
                result+=self.weightSum(i,level+1)
        return result

0 0
原创粉丝点击