364. 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)

Solution 1: DFS 3ms

这道题是之前那道Nested List Weight Sum的拓展,与其不同的是,这道题的深度越深,权重越小,和之前刚好相反。但是解题思路没有变,还可以用DFS来做,那么由于遍历的时候不知道最终的depth有多深,则不能遍历的时候就直接累加结果,我最开始的想法是在遍历的过程中建立一个二维数组,把每层的数字都保存起来,然后最后知道了depth后,再来计算权重和,比如题目中给的两个例子,建立的二维数组分别为:

[[1,1],2,[1,1]]:

1 1 1 1
2
[1,[4,[6]]]:

1
4
6

这样我们就能算出权重和了,参见代码如下: 其实上面的方法可以简化,由于每一层的数字不用分别保存,每个数字分别乘以深度再相加,跟每层数字先相加起来再乘以深度是一样的,这样我们只需要一个一维数组就可以了,只要把各层的数字和保存起来,最后再计算权重和即可:

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * class NestedInteger {
 *   public:
 *     // Constructor initializes an empty nested list.
 *     NestedInteger();
 *
 *     // Constructor initializes a single integer.
 *     NestedInteger(int value);
 *
 *     // 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;
 *
 *     // Set this NestedInteger to hold a single integer.
 *     void setInteger(int value);
 *
 *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.
 *     void add(const NestedInteger &ni);
 *
 *     // 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 {
    void dfs(NestedInteger& l, vector<int>& v, int depth) {
        if (depth >= v.size()) v.push_back(0);
        if (l.isInteger()) {
            v[depth] += l.getInteger();
        } else {
            for (auto&a: l.getList()) {
                dfs(a, v, depth+1);
            }
        }
    }
public:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        vector<int> v;
        for (auto&a : nestedList) {
            dfs(a,v,0);
        }

        int res = 0;
        for (int i = 0; i < v.size(); ++i) {
            res += (v.size()-i)*v[i];
        }
        return res;
    }
};

Solution 2: 3ms

下面这个方法就比较巧妙了,由史蒂芬大神提出来的,这个方法用了两个变量unweighted和weighted,非权重和跟权重和,初始化均为0,然后如果nestedList不为空开始循环,先声明一个空数组nextLevel,遍历nestedList中的元素,如果是数字,则非权重和加上这个数字,如果是数组,就加入nextLevel,这样遍历完成后,第一层的数字和保存在非权重unweighted中了,其余元素都存入了nextLevel中,此时我们将unweighted加到weighted中,将nextLevel赋给nestedList,这样再进入下一层计算,由于上一层的值还在unweighted中,所以第二层计算完将unweighted加入weighted中时,相当于第一层的数字和被加了两次,这样就完美的符合要求了,这个思路又巧妙又牛B,大神就是大神啊,参见代码如下:

class Solution {
public:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int unweighted = 0, weighted = 0;
        while (!nestedList.empty()) {
            vector<NestedInteger> nextLevel;
            for (auto a:nestedList) {
                if (a.isInteger()) unweighted += a.getInteger();
                else nextLevel.insert(nextLevel.end(), a.getList().begin(), a.getList().end());
            }
            weighted += unweighted;
            nestedList = nextLevel;
        }
        return weighted;
    }
};

Solution 3: BFS 3ms

下面这种算法是常规的BFS解法,利用上面的建立两个变量unweighted和weighted的思路,大体上没什么区别:

class Solution {
public:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int unweighted = 0, weighted = 0;
        queue<vector<NestedInteger>> q;
        q.push(nestedList);
        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; ++i) {
                vector<NestedInteger> t = q.front(); q.pop();
                for (auto& a:t) {
                    if (a.isInteger()) unweighted += a.getInteger();
                    else q.push(a.getList());
                }
            }
            weighted += unweighted;
        }
        return weighted;
    }
};

results matching ""

    No results matching ""