0%

Nested List Weight Sum

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.

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

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
DFS
*/
int result = 0;
public int depthSum(List<NestedInteger> nestedList) {
dfs(nestedList, 1);
return result;
}
public void dfs(List<NestedInteger> nestedList, int depth){
for ( int i = 0; i < nestedList.size(); i++){
NestedInteger temp = nestedList.get(i);
if ( !temp.isInteger() ){
dfs(temp.getList(), depth+1);
}else{
result += temp.getInteger() * depth;
}
}
}