算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 嵌套列表权重和,我们先来看题面:
https://leetcode-cn.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.
给定一个嵌套的整数列表,请返回该列表按深度加权后所有整数的总和。
每个元素要么是整数,要么是列表。同时,列表中元素同样也可以是整数或者是另一个列表。
示例
示例 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这个变量记录当前的深度(也就是权重),
当类型是数字的时候,直接返回weight和数字的乘积,
当类型是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)
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文:
LeetCode刷题实战325:和等于 k 的最长子数组长度