[Swift]LeetCode339. 嵌套鏈表權重和 $ Nested List Weight Sum

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-gyaqevef-ho.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given a nested list of integers, return the sum of all integers in the list weighted by their depth.git

Each element is either an integer, or a list -- whose elements may also be integers or other lists.github

Example 1:
Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1)微信

Example 2:
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)spa


給定一個嵌套的整數列表,返回列表中按深度加權的全部整數的和。code

每一個元素要麼是一個整數,要麼是一個列表——其元素也能夠是整數或其餘列表。htm

例1:blog

給定列表[[1,1],2,[1,1]],返回10。(深度2處4個1,深度1處1個2)element

例2:get

給定列表[1,[4,[6]]],返回27。(深度1處1個1,深度2處1個4,深度3處1個6;1+4*2+6*3=27)


Solution:

 1 class Solution {
 2     func depthSum(_ nestedList:inout [NestedInteger]) -> Int {
 3         retrurn helper(&nestedList, 1)
 4     }
 5     
 6     func helper(_ nl:inout [NestedInteger],_ depth:Int) -> Int
 7     {
 8         var res:Int = 0
 9         for a in nl
10         {
11             if let num:Int = Int(a)
12             {
13                  res += (num * depth)
14             }
15             else
16             {
17                 var list = a.getList()
18                 res +=  helper(&list, depth + 1)
19             }
20         }
21         return res
22     }
23 }
相關文章
相關標籤/搜索