这是我参与8月更文挑战的第24天,活动详情查看:8月更文挑战
难度: 中等
题目描述
给定一个嵌套的整数列表 nestedList ,每个元素要么是整数,要么是列表。同时,列表中元素同样也可以是整数或者是另一个列表。
整数的 深度 是其在列表内部的嵌套层数。例如,嵌套列表 [1,[2,2],[[3],2],1] 中每个整数的值就是其深度。
请返回该列表按深度加权后所有整数的总和。
示例 1:
输入:nestedList = [[1,1],2,[1,1]] 输出:10 解释:因为列表中有四个深度为 2 的 1 ,和一个深度为 1 的 2。
示例 2:
输入:nestedList = [1,[4,[6]]] 输出:27 解释:一个深度为 1 的 1,一个深度为 2 的 4,一个深度为 3 的 6。所以,1 + 42 + 63 = 27。
示例 3:
输入:nestedList = [0] 输出:0 提示:
1 <= nestedList.length <= 50 嵌套列表中整数的值在范围 [-100, 100] 内 任何整数的最大 深度 都小于或等于 50
概要 这是一个简单的递归问题,可以很好的介绍深度优先搜索算法。
题解
深度优先遍历
算法 常规解法 DFS
- 很自然的想到用递归解决这个问题。
- 依次遍历嵌套的整数,同时记录当前的深度 dd。
- 遍历到的整数是 nn,就向结果加上 n \times dn×d。
- 遍历到的是一个列表,我们就递归求解这个列表的和,同时将深度变成 d+1d+1。
class Solution:
def depthSum(self, nestedList: List[NestedInteger]) -> int:
def dfs(nestedlist,deps):
ans = 0
for l in nestedlist:
if l.getList():
ans += dfs(l.getList(),depth + 1)
elif l.getInteger():
ans += deps * l.getInteger()
return ans
return dfs(nestedList,1)
思路二(白话文):
大问题可以拆成很多个类型相同的小问题:
- 观察到可以用递归解,用 wgt 这个变量记录当前的深度,
- 当类型是数字的时候,直接返回 wgt 和数字的乘积,
- 当类型是 nestedList 的时候,就需要对其中每一个元素进行递归处理。
class Solution(object):
def depthSum(self, nestedList):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
def Sum(wgt, l):
if l.isInteger():
return wgt * l.getInteger()
return sum(Sum(wgt + 1, item) for item in l.getList())
return sum(Sum(1, i) for i in nestedList)