题目
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.
答案
class Solution {
public int depthSum(List<NestedInteger> nestedList) {
return recur(nestedList, 1);
}
public int recur(List<NestedInteger> nestedList, int depth) {
int total = 0;
for(int i = 0; i < nestedList.size(); i++) {
NestedInteger ni = nestedList.get(i);
if(ni.isInteger()) {
total += depth * ni.getInteger();
}
else {
total += recur(ni.getList(), depth + 1);
}
}
return total;
}
}