364. Nested List Weight Sum II

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.

Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.

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)

解法1:

一个递归的办法就可以解决。因为weight现在是从bottom到top,所以要先计算出maxdepth。这一步也需要用递归完成。
然后把depth作为一个参数pass到每一层就可以了。
C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class Solution {
public int depthSumInverse(List<NestedInteger> nestedList) {
if (nestedList == null || nestedList.size() == 0) {
return 0;
}
// get the max sum;
int maxDepth = getMaxDepth(nestedList);
return helper(nestedList, maxDepth);
}
private int getMaxDepth(List<NestedInteger> nestedList) {
int max = 1;
for (int i = 0; i < nestedList.size(); i++) {
NestedInteger item = nestedList.get(i);
if (item.isInteger()) {
max = Math.max(max, 1);
} else {
max = Math.max(max, getMaxDepth(item.getList()) + 1);
}
}
return max;
}
private int helper(List<NestedInteger> nestedList, int depth) {
int sum = 0;
for (int i = 0; i < nestedList.size(); i++) {
NestedInteger item = nestedList.get(i);
if (item.isInteger()) {
sum += depth * item.getInteger();
} else {
sum += helper(item.getList(), depth - 1);
}
}
return sum;
}
}