0%

Nested List Weight Sum II

Question

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:

Input: [[1,1],2,[1,1]]
Output: 8
Explanation: Four 1’s at depth 1, one 2 at depth 2.

Solution

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
/*
@param: List<NestedInteger> nestedList
@return: int
Algorithm: 由于题目深度与之前的题目不一样,是maxDepth - curDepth
直观思路是先dfs一般求maxDepth,之后用maxDepth-curDepth计算
后来可以推出一个数学解,one pass solution。
例如 [1,[2,[3]]] 3x+2y+z = (maxDepth+1)*(x+y+z)-(x+2y+3z);
*/
int max = 1;
int sum;
int res;
public int depthSumInverse(List<NestedInteger> nestedList) {
int n = nestedList.size();
if (n == 0) return 0;

dfs(nestedList, 1);
return sum * (max+1) - res;
}


public void dfs(List<NestedInteger> nestedList, int depth) {
max = Math.max(depth, max);
for (int i = 0; i < nestedList.size(); i++) {
if (nestedList.get(i).isInteger()) {
res += nestedList.get(i).getInteger() * depth;
sum += nestedList.get(i).getInteger();
}else {
dfs(nestedList.get(i).getList(), depth+1);
}
}
}