339. Nested List Weight Sum

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;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容