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.
/* @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; publicintdepthSumInverse(List<NestedInteger> nestedList){ int n = nestedList.size(); if (n == 0) return0; dfs(nestedList, 1); return sum * (max+1) - res; }
publicvoiddfs(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); } } }