[LeetCode][Search] 339. Nested List Weight Sum

Problem

More LeetCode Discussions
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 + 42 + 63 = 27)

Solution

用DFS搜索,dep表示深度。

/**
 * // 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:
    int getSum(int dep, vector<NestedInteger> &nestedList) {
        int total = 0;
        for(int i = 0; i < nestedList.size(); i++) {
            if (nestedList[i].isInteger()) {
                total += nestedList[i].getInteger() * dep;
            } else {
                total += getSum(dep + 1, nestedList[i].getList());
            }
        }
        
        return total;
    }
    
    int depthSum(vector<NestedInteger>& nestedList) {
        return getSum(1, nestedList);
    }
};
    原文作者:楷书
    原文地址: https://www.jianshu.com/p/37d20f8adf7a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞