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:

Input: [[1,1],2,[1,1]]
Output: 8 
Explanation: Four 1's at depth 1, one 2 at depth 2.

Example 2:

Input: [1,[4,[6]]]
Output: 17 
Explanation: One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17.

方法1: 2-d 数组

和339一样,但是第一遍历先延路按depth储存vector<vector>, 递归结束之后总深度已知,再遍历一遍计算sum。

易错点:

每次dfs发起时先检查有没有超出result的边界,因为result一开始并不知道到底有多深,走到哪建到哪,比如
[[1,1],2,[1,1]]

遇到第一个[1, 1]时需要建立新层
遇到第一个1 时需要建立新层
遇到2和后面的[1, 1]都不需要

/**
 * // 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 {
public:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        if (nestedList.size() == 0) return 0;
        vector<vector<int>> result;
        dfs(nestedList, result, 0);
        int sum = 0;
        int n = result.size();
        for (int i = n - 1; i >= 0; i--){
            for (int a: result[i]){
                sum += a * (n - i);
            }
        }
        return sum;
    }
    
    void dfs(vector<NestedInteger> & nestedList, vector<vector<int>> & result, int depth){
        if (depth == result.size()){
            result.push_back({});
        }
        for (NestedInteger a: nestedList){
            if (a.isInteger()){
                result[depth].push_back(a.getInteger());
            } 
            else {
                // 这里需要用getList()才能返还 NestedInteger 的类型
                // dfs(a, sum, depth + 1); 
                dfs(a.getList(), result, depth + 1);
            }
        }
    return;
    }
    
};

方法2: 1-d 数组

考虑到先weight再sum和先sum再weight没有区别,只用1-d数组累加每个level的sum。

class Solution {
public:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int sum = 0;
        vector<int> res;
        nestHelper(nestedList, 0, res);
        for (int i = 1; i <= res.size(); i++) {
            sum += i * res[res.size() - i];
        }
        return sum;
    }
    
    void nestHelper(vector<NestedInteger> & nestedList, int depth, vector<int> & res) {
        if (depth == res.size()) res.push_back({0});
        for (NestedInteger a: nestedList) {
            if (a.isInteger()) res[depth] += a.getInteger();
            else {
                nestHelper(a.getList(), depth + 1, res);
            }
        }
        return;
    }
};

方法3: BFS

not working
depth 计算错误
[1,[4,5,[6],[7]]]

class Solution {
public:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        if (nestedList.size() == 0) return 0;
        vector<int> result;
        queue<vector<NestedInteger>> myQueue;
        myQueue.push(nestedList);
            
        bfs(myQueue, result);
        
        int sum = 0;
        int n = result.size();
        for (int i = n - 1; i >= 0; i--){
                sum += result[i] * (n - i);
            }
        
        return sum;
    }
    
//     result = {2}
//     q = [[1, 1],[1, 1]]
//     a = []
//     N = 3
//     i = 2
//     depth = 1;
        
    void bfs(queue<vector<NestedInteger>>& q, vector<int> & result){
        int depth = 0;
        while (!q.empty()){
            
            printVector(result);
            vector<NestedInteger> a = q.front();
            int N = a.size();
            q.pop();
            
            for (int i = 0; i < N; i++){
                if (depth == result.size()){
                    result.push_back(0);
                }
                if (a[i].isInteger()){
                    result[depth] += a[i].getInteger();      
                } 
                else {
                    // 这里需要用getList()才能返还 NestedInteger 的类型
                    // dfs(a, sum, depth + 1);   
                    q.push({a[i].getList()});        
                }
            }
            depth ++;
        }    
       
        return;
    }
    
    void printVector(vector<int> & a){
        for (int i: a)
            cout << i << endl;
        cout<< endl;
    }
};

方法4:

http://www.cnblogs.com/grandyang/p/5615583.html
这个方法用了两个变量unweighted和weighted,非权重和跟权重和,初始化均为0,然后如果nestedList不为空开始循环,先声明一个空数组nextLevel,遍历nestedList中的元素,如果是数字,则非权重和加上这个数字,如果是数组,就加入nextLevel,这样遍历完成后,第一层的数字和保存在非权重和unweighted中了,其余元素都存入了nextLevel中,此时我们将unweighted加到weighted中,将nextLevel赋给nestedList,这样再进入下一层计算,由于上一层的值还在unweighted中,所以第二层计算完将unweighted加入weighted中时,相当于第一层的数字和被加了两次,这样就完美的符合要求了。

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;
    }
}; 

方法5: BFS + weighting

下面这种算法是常规的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 if (!a.getList().empty()) q.push(a.getList());
                }
            }
            weighted += unweighted;
        }
        return weighted;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值