?LeetCode刷題實戰(zhàn)339:嵌套列表權(quán)重和
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.
示例
示例 1:
輸入: [[1,1],2,[1,1]]
輸出: 10
解釋: 因為列表中有四個深度為 2 的 1 ,和一個深度為 1 的 2。
示例 2:
輸入: [1,[4,[6]]]
輸出: 27
解釋: 一個深度為 1 的 1,一個深度為 2 的 4,一個深度為 3 的 6。所以,1 + 4*2 + 6*3 = 27。
解題
大問題可以拆成很多個類型相同的小問題,
所以觀察到可以用遞歸解,所以用weight這個變量記錄當(dāng)前的深度(也就是權(quán)重),
當(dāng)類型是數(shù)字的時候,直接返回weight和數(shù)字的乘積,
當(dāng)類型是nestedList的時候,就需要對其中每一個元素進行遞歸處理。
class Solution(object):
def depthSum(self, nestedList):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
def Sum(weight, l):
if l.isInteger():
return weight * l.getInteger()
return sum(Sum(weight + 1, item) for item in l.getList())
return sum(Sum(1, i) for i in nestedList)
