题目链接: https://leetcode.com/problems/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]]
, 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, 因为数组中的每一个元素都可能包含另外一个数组, 因此这是一个多层嵌套的关系, 但是嵌套的层数需要有个记录, 所以我们只需要另外写一个函数, 记录当前是第几层即可.
代码如下:
/**
* // 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 &getList() const;
* };
*/
class Solution {
public:
int DFS(vector& nestedList, int depth)
{
int sum = 0;
for(auto val: nestedList)
{
if(val.isInteger())
sum += val.getInteger()*depth;
else sum += DFS(val.getList(), depth+1);
}
return sum;
}
int depthSum(vector& nestedList) {
return DFS(nestedList, 1);
}
};