一.题目:
Example 1:
Given the list [[1,1],2,[1,1]], return 8. (four 1’s at depth 1, one 2 at depth 2)
Example 2:
Given the list [1,[4,[6]]], return 17. (one 1 at depth 3, one 4 at depth 2, and one 6 at depth 1;
13 + 42 + 6*1 = 17)
二.解题思路:
这道题可以先利用递归求得最深的深度同时记录该深度下所有的数字的和,然后再遍历列表中的每个元素,得到结果.
import collections
nums = [[1, [1, [2, 3]], 1], 2, [1, 1]]
result = collections.defaultdict(int)
def dfs(nums,depth):
if not nums:
return
for num in nums:
if type(num) != list:
result[depth] += num
else:
dfs(num, depth+1)
dfs(nums, 1)
#print result
#{1: 2, 2: 4, 3: 1, 4: 5})
#在加权求和时需要将键的数值调换
n_sum = 0
depths = result.keys()
max_dep = max(result.keys()) +1
for i in depths:
n_sum += result[i] * (max_dep - i)
#print n_sum
return n_sum
三.总结
算是简单题目,思路比较容易得到.需要用到递归求深度.递归的题目还是需要多练啊,生疏....