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 + 4x2 + 6x3 = 27)

分析:

这个题目的DFS本身并没有那么困难,但是其重点在于训练快速阅读interface的能力。这个题目是LinkedIn的考题,在面试的紧张环境下,能保证读好interface理解好每个函数的功能吗?

第一遍做的时候我理解错了题意,好烦...

题目来自leetcode, lintcode上没有

解法:

/**
 * // 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 level, int& sum) {
        for (int i = 0; i < nestedList.size(); i++) {
            if (nestedList[i].isInteger() ) {
                sum += (nestedList[i].getInteger() * level);
                //return;
            } else {
                vector<NestedInteger> temp = nestedList[i].getList();
                dfs(temp, level + 1, sum);
            }
        }
    }

    int depthSum(vector<NestedInteger>& nestedList) {
        if (nestedList.size() == 0) {
            return 0;
        } 

        int sum = 0;
        dfs(nestedList, 1, sum);
        return sum;
    }
};

results matching ""

    No results matching ""