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:Given the list[[1,1],2,[1,1]], return10. (four 1's at depth 2, one 2 at depth 1)
Example 2:Given the list[1,[4,[6]]], return27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27)
这题最简单的解法用 recursion! 用不好啊, 用不好!!!!!!
谁能告诉我咋样贴代码不乱码呀。
public class Solution {
public int depthSum(ListnestedList) {
if(nestedList == null || nestedList.size() < 1){
return 0;
}
return help(nestedList, 1);
}
private int help(ListnestedList, int weight){
int sum = 0;
for(NestedInteger nestedInt : nestedList){
if(nestedInt.isInteger()){
sum += nestedInt.getInteger() * weight;
else{
sum += help(nestedInt.getList(), weight + 1);
}
}
return sum;
}
}