首页 > 其他 > 详细

339. Nested List Weight Sum

时间:2016-09-24 07:02:30      阅读:178      评论:0      收藏:0      [点我收藏+]

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]], return 10. (four 1‘s at depth 2, one 2 at depth 1)

Example 2:
Given the list [1,[4,[6]]], return 27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27)

DFS

public int DepthSum(IList<NestedInteger> nestedList) {
        return Depth(nestedList,1);
    }
    
    public int Depth(IList<NestedInteger> nestedList, int depth)
    {
        int res =0;
        if(nestedList.Count()==0)
        {
            return res;
        }
        else
        {
            foreach(var n in nestedList)
            {
                if(n.IsInteger()) res += n.GetInteger()* depth;
                else    res += Depth(n.GetList(),depth+1);
            }
            return res;
        }
    }

 

339. Nested List Weight Sum

原文:http://www.cnblogs.com/renyualbert/p/5902320.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!