Skip to content

Latest commit

 

History

History
164 lines (126 loc) · 4.63 KB

364. Nested-List-Weight-Sum-II.md

File metadata and controls

164 lines (126 loc) · 4.63 KB

Description

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.

Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.

Example 1:

Input: [[1,1],2,[1,1]]
Output: 8
Explanation: Four 1's at depth 1, one 2 at depth 2.

Example 2:

Input: [1,[4,[6]]]
Output: 17
Explanation: One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17.

python solution

接上道题Nested List Weight Sum II, 这道题也有点点难懂。可以这样理解:

  • 最里层中括号的权值为1,第二层的权值为2……

例如[1,[4,[6]]]],6在最里层,所以权值为1;4在第2层,权值为2;1在第三层,权值为3.

我没有使用标准的BFS解法,而是借助了上道题已经写好的DFS

其实这道题也可以看作DFS问题,和上一道题恰恰相反。上一道题越里层的元素权值越大,这道题是越外层的元素权值越大。思路如下:

  • 先求出总的深度depth
  • 再用这个depth进行DFS,每深入一层,这个depth就要减1,直接最深层这个depth的值就变为了1.

所以,总结一下:

  • 上一道题我们是最后才知道嵌套列表的深度
  • 这一道题我们一开始就要知道嵌套列表的深度

我的python解法如下:

# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
# class NestedInteger(object):
#    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(object):

    def __init__(self):
        self.depth = 1

    # 计算整个列表的深度
    def calcDepth(self, nestedList, depth):
        self.depth = max(depth, self.depth)
        for i in nestedList:
            if not i.isInteger():
                self.calcDepth(i.getList(), depth + 1)

    def depthSumInverse(self, nestedList):
        """
        :type nestedList: List[NestedInteger]
        :rtype: int
        """
        def calc(nestedList, depth):
            res = 0
            for i in nestedList:
                if i.isInteger():
                    res += i.getInteger() * depth
                else:
                    res += calc(i.getList(), depth - 1)  # 注意这里变成了减1
            return res

        # 一开始就要求得这个列表的深度
        self.calcDepth(nestedList, 1)

        return calc(nestedList, self.depth)

标准的BFS解法:

class Solution(object):
    def depthSumInverse(self, nestedList):
        """
        :type nestedList: List[NestedInteger]
        :rtype: int
        """

        cur_level = nestedList
        stack = []

        # bfs
        while cur_level:
            t = 0
            next_level = []
            for element in cur_level:
                if element.isInteger():
                    t += element.getInteger()
                else:
                    next_level.extend(element.getList())
            cur_level = next_level
            stack.append(t)

        # cal. res
        res = 0
        for i, n in enumerate(stack[::-1]):
            res += (i + 1) * n
        return res