【题目描述】
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
Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1, 4 * 1 * 2 + 1 * 2 * 1 = 10)
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)
给一个嵌套的整数列表, 返回列表中所有整数由它们的深度加权后的总和. 每一个元素可能是一个整数或一个列表(其元素也可能是整数或列表)
样例
给出列表 [[1,1],2,[1,1]], 返回 10. (4个'1'的深度是 2, 1个'2'的深度是1, 4 * 1 * 2 + 1 * 2 * 1 = 10)
给出列表 [1,[4,[6]]], 返回 27. (1个 '1' 的深度是1, 1个 '4' 的深度是2, 以及1个 '6'的深度是3, 1 + 4 * 2 + 6 * 3 = 27)
【题目链接】
www.lintcode.com/en/problem/nested-list-weight-sum/
【题目解析】
这道题定义了一种嵌套链表的结构,链表可以无限往里嵌套,规定每嵌套一层,深度加1,让我们求权重之和,就是每个数字乘以其权重,再求总和。
遍历给的嵌套链表的数组,对于每个嵌套链表的对象,调用getSum函数,并赋深度值1,累加起来返回。在getSum函数中,首先判断其是否为整数,如果是,则返回当前深度乘以整数,如果不是,那么再遍历嵌套数组,对每个嵌套链表再调用递归函数,将返回值累加起来返回即可。
【参考答案】