Facebook
From minhhnh, 2 Months ago, written in Python.
Embed
Download Paste or View Raw
Hits: 175
  1. ## https://www.lintcode.com/problem/905
  2. class Solution:
  3.     def depthSumInverse(self, nestedList):
  4.         max_depth = 0
  5.  
  6.         def dfs(lst, depth):
  7.             nonlocal max_depth
  8.             weighted_sum, unweighted_sum = 0, 0
  9.             max_depth = max(max_depth, depth)
  10.             for i in lst:
  11.                 if isinstance(i, list):
  12.                     result = dfs(i, depth + 1)
  13.                     weighted_sum += result[0]
  14.                     unweighted_sum += result[1]
  15.                 else:
  16.                     weighted_sum += i * (-depth)
  17.                     unweighted_sum += i
  18.             return weighted_sum, unweighted_sum
  19.  
  20.         weighted_sum, unweighted_sum = dfs(nestedList, 1)
  21.         return weighted_sum + unweighted_sum * (max_depth + 1)
  22.  
  23.  
  24. print(Solution().depthSumInverse([[1, 1], 2, [1, 1]]))
  25. print(Solution().depthSumInverse([1, [4, [6]]]))
  26.