您的位置:首页 > 其它

[leetcode] 364. Nested List Weight Sum II 解题报告

2016-06-23 14:52 549 查看
题目链接: https://leetcode.com/problems/nested-list-weight-sum-ii/

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.

Different from the previous question where weight is increasing from root to leaf, now
the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.

Example 1:

Given the list 
[[1,1],2,[1,1]]
, return 8. (four 1's
at depth 1, one 2 at depth 2)

Example 2:

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

思路: 和之前的一题不同在于这题结点的权值是越靠近根部越高, 而在叶子结点则越低. 所以在找到最大深度之前你是无法计算的, 也就是说我们可以将每个值和他的深度边搜索边存起来, 并且计算最大深度是多少. 最后将所有的点遍历完之后就得到了所有需要的信息. 这时就可以根据最大深度和每一个点的深度来计算加权值了.

代码如下:

/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
*   public:
*     // Return true if this NestedInteger holds a single integer, rather than a nested list.
*     bool isInteger() const;
*
*     // Return the single integer that this NestedInteger holds, if it holds a single integer
*     // The result is undefined if this NestedInteger holds a nested list
*     int getInteger() const;
*
*     // Return the nested list that this NestedInteger holds, if it holds a nested list
*     // The result is undefined if this NestedInteger holds a single integer
*     const vector<NestedInteger> &getList() const;
* };
*/
class Solution {
public:
void DFS(vector<NestedInteger>& nestedList, int depth)
{
maxDepth = max(maxDepth, depth);
for(auto val: nestedList)
{
if(!val.isInteger()) DFS(val.getList(), depth+1);
else nums.push_back(make_pair(val.getInteger(), depth));
}
}

int depthSumInverse(vector<NestedInteger>& nestedList) {
if(nestedList.size() ==0) return 0;
DFS(nestedList, 1);
for(auto val: nums) result+= (maxDepth-val.second+1)*val.first;
return result;
}
private:
vector<pair<int, int>> nums;
int maxDepth = 0, result = 0;
};


还有一种更为简单的方法,利用每一层将当前整数加起来,然后往后遍历多一层就将前面已经加过的数再加一遍.非常巧妙!

class Solution {
public:
int depthSumInverse(vector<NestedInteger>& nestedList) {
int unweighted = 0, weighted = 0;
while(nestedList.size())
{
vector<NestedInteger> nextLevel;
for(auto val: nestedList)
{
if(val.isInteger()) unweighted += val.getInteger();
else for(auto v: val.getList()) nextLevel.push_back(v);
}
weighted += unweighted;
nestedList = nextLevel;
}
return weighted;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode DFS