【EASY】Nested List Weight Sum
发布于:2019-03-01 17:29,阅读数:493,点赞数:0
# 问题 原题链接:[https://leetcode.com/problems/nested-list-weight-sum/](https://leetcode.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. Example 1: ``` Input: [[1,1],2,[1,1]] Output: 10 Explanation: Four 1's at depth 2, one 2 at depth 1. ``` Example 2: ``` Input: [1,[4,[6]]] Output: 27 Explanation: One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27. ``` # 分析过程 - 输入:一个嵌套的数组 - 输出:加权和,权值是该层的深度 - 思路:一个简单的递归。遍历数组,如果是数字就加,如果是列表就递归,并权重+1。 # 解决方法 ```swift class Solution { func _depthSum(forList input: [NestedInteger], level: Int) -> Int { var sum = 0 for i in input { if i.isInteger() { sum += i.getInteger() * level } else { sum += _depthSum(forList: i.getList(), level: level + 1) } } return sum } func depthSum(_ nestedList: [NestedInteger]) -> Int { return _depthSum(forList: nestedList, level: 1) } } ```
评论:0条